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 char 转换为小写/大写

java - 在java中计算bigdecimal的sigmoid值

java - 如何动态反编译内存中的类对象?

java - 如何在 java 中运行 JavaScript 方法?(我需要创建程序来下载大约 10k 首轨道)

c - 需要创建一个返回 int 的函数,该函数基于哪个 char 参数具有更多大写字母

java - 在 Java 中从列表中提取子字符串

java - mvn 发布 :perform fails in java 8 - added javadoc plugin

c++ - 用空格填充字符串有时会破坏字符串迭代器

python - 根据前面的字符串返回子字符串

c++ - std::string 在开始和结束之间替换