如何获取字符串中所有单词出现的索引?

时间:2019-03-06 09:47:38

标签: android string indexing

我想获取所有string_to_be_search出现的索引

输入:

String line="hello this is prajakta , how are you?? hello this is prajakta!"
String text_to_search= "hello this is prajakta"

这里出现的text_to_search为2,所以我需要起始索引列表

输出:

List l=[0,39]

我也在下面尝试了一个代码

 public List getIndexesOfMultipleOccuredString(String originalString,String textToSearch) {
    int i, last = 0, count = 0;
    List l = new ArrayList();
    do {
        i = originalString.indexOf(textToSearch, last);
        if (i != -1) l.add(i);
        last = i + textToSearch.length();
    } while (i != -1);
    return l;
}

但是 如果我的输入如下

String line="hello this is prajakta ,i love to drive car and i am a carpainter"
String text_to_search="car"

输出:

It gives me two indexes as carpainter contains car which i don't want
Output should be [39]

1 个答案:

答案 0 :(得分:0)

这是使用正则表达式(单词匹配)的方法

String line= "hello this is prajakta , how are you?? hello this is prajakta!";
String text_to_search = "\\bhello this is prajakta\\b";
ArrayList<Integer> list = new ArrayList<>();
Pattern p = Pattern.compile(text_to_search);
Matcher m = p.matcher(line);

while (m.find()) {
    list.add(m.start());
}

Log.i("All occurrences", "values are " + list.toString());

输出: [0, 39]

如果您使用这些字符串进行搜索

String line="hello this is prajakta ,i love to drive car and i am a carpainter";
String text_to_search="car";// use as "\\bcar\\b"

输出 [40]