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

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);
        
    }
}

你可能感兴趣的:([小练习] 计算在一个字符串中指定字符串出现的次数)