java - 字符串中子字符串的出现次数

标签 java string

为什么以下算法对我没有停止? (str 是我要搜索的字符串,findStr 是我要查找的字符串)

String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;

while (lastIndex != -1) {
    lastIndex = str.indexOf(findStr,lastIndex);

    if( lastIndex != -1)
        count++;

    lastIndex += findStr.length();
}

System.out.println(count);

最佳答案

如何使用StringUtils.countMatches来自 Apache Commons Lang?

String str = "helloslkhellodjladfjhello";
String findStr = "hello";

System.out.println(StringUtils.countMatches(str, findStr));

输出:

3

关于java - 字符串中子字符串的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/767759/

相关文章:

c++ - C++ 中的 Unicode 和 std::string

string - 如何从Elixir中的字符串中删除前n个字符?

c - 函数调用会跳过函数的语句

c - 为什么下面程序中的 fgets 函数(请参阅详细信息)将字符串的长度解释为多一个字符?

java - JAVA 中读取文件、操作其数据以及写入另一个文件的优化解决方案

java - WebSockets (ServerEndPoint) 配置

java - 以 HashMap<string,integer> 作为其类型对 TreeSet 进行排序

java - hibernate 锁定表

java - 无法获取资源

java - 正则表达式 - 使用正则表达式搜索字符串并从原始字符串中提取匹配项