0

我使用以下代码

 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

怎么做?帮助

4

1 回答 1

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();
于 2013-02-28T14:02:18.327 回答