我使用以下代码
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);
结果,我找到了单词的第一个索引:
创建 creater34r3
但是我只需要找到单词create
怎么做呢?帮助
最佳答案
如果我理解您在字符串中查找整个单词的要求(如果存在),那么这样如何:
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());
}
输出将是创建
但我发现您需要实际的索引 - 如果是这样,您可以将其添加到 while block 中:
int start = matcher.start();
int end = matcher.end();
关于java - 如何找到单词的第一个索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15137421/