如何找到单词的第一个索引?

时间:2013-02-28 14:01:54

标签: java string substring

我使用以下代码

 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

字样的第一个索引

怎么做?帮助

1 个答案:

答案 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();