且构网

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

获取另一个字符串中一个字符串的出现次数

更新时间:2021-11-21 22:01:47

您也可以尝试:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    String word8 = sc.nextLine();
    String word9 = sc.nextLine();
    int index = word8.indexOf(word9);
    sc.close();
    int occurrences = 0;
    while (index != -1) {
        occurrences++;
        word8 = word8.substring(index + 1);
        index = word8.indexOf(word9);
    }
    System.out.println("No of " + word9 + " in the input is : " + occurrences);
}