我使用以下代码
String fulltext = "I would like to create some text and i dont know what creater34r3, ";
String subtext = "create";
int ind = -1;
do {
ind = fulltext.indexOf(subtext, ind + subtext.length());
} while (ind != -1);
结果,我找到了单词的第一个索引:
create creater34r3
但我需要找到仅 create
怎么做?帮助
答案 0 :(得分:1)
如果我理解你要求在字符串中找到整个单词,如果它们存在,那么如何:
String fulltext = "I would like to create some text and i dont know what creater34r3, ";
String subtext = "create";
Pattern pattern = Pattern.compile("\\b(" + subtext + ")\\b");
Matcher matcher = pattern.matcher(fulltext);
while (matcher.find()) {
System.out.println(matcher.group());
}
输出为create
但是我发现你需要实际索引 - 如果是这样你可以将它添加到while块:
int start = matcher.start();
int end = matcher.end();