[小练习] 计算在一个字符串中指定字符串出现的次数

public class Test {
    public static void main(String[] args) {
        String str = "How are you, you're so beautiful. Nice to meet you.";
        String s = "you";
        int fromIndex = 0;
        int count = 0;
        while((fromIndex = str.indexOf(s, fromIndex)) != -1) {
            fromIndex = fromIndex + s.length();
            str = str.substring(fromIndex);
            count++;
            fromIndex = -1;
            // System.out.println("str is " + str);
            // System.out.println("count = " + count);
        }
        System.out.println(count);
    }

或者
public class Main
{
    public static void main(String[] args) {
        String str = "How are you, you're so beautiful. Nice to meet you.";
        String s = "you";
        int count = str.split(s).length - 1;
        System.out.println("count: " + count);
        
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容