且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何查找字符串对象在java中重复多少次?

更新时间:2022-11-07 22:51:09

最简单的方法是使用 indexOf 在循环中,每次找到单词时推进起始索引:

The simplest way is to use indexOf in a loop, advancing the starting index each time that you find the word:

int ind = 0;
int cnt = 0;
while (true) {
    int pos = first.indexOf(second, ind);
    if (pos < 0) break;
    cnt++;
    ind = pos + 1; // Advance by second.length() to avoid self repetitions
}
System.out.println(cnt);

如果一个单词包含自我重复,这将多次找到该单词。请参阅上面的评论以避免此类重复查找。

This will find the word multiple times if a word contains self-repetitions. See the comment above to avoid such "duplicate" finds.

演示想法