如何查找字符串对象在java中重复多少次? [英] How to find how many times does a string object repeat in java?

查看:798
本文介绍了如何查找字符串对象在java中重复多少次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用String对象:

I have to String objects:

String first = "/Some object that has a loop in it object/";
String second = "object";

我需要做的是找到第二个对象在第一个对象中重复的次数,可以你能告诉我怎么做吗?

What I need to do is find how many times does the second object repeat in the first object, can you please show me how to do that?

推荐答案

最简单的方法是使用 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.

演示想法

这篇关于如何查找字符串对象在java中重复多少次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆