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

标签 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);

结果,我找到了单词的第一个索引:

创建 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/

相关文章:

java - 馆藏副本

java - 将字符串转换为 Int

string - 在单元测试中使用与被测系统相同的常量是个好主意吗?

excel - VBA 中的 Unicode 字符串文字

Python - 有一个具有相同变量的子循环

java - Java中的可扩展双链树实现

java - PDFBox convertToImage 无法正确呈现某些 PDF

java - 创建实体并生成数据库表 (JSF/JPA)

java - java中计算特定字符的数量

objective-c - iOS/Objective-C : Attempting to Scan a string for substrings which will be assigned to multiple NSStrings