15、基础编程:计算字符串中子串出现的次数。

1、代码: 

package demo15;

import java.util.Scanner;

//计算字符串中子串出现的次数
public class Demo15 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入字符串:");
        String str = sc.nextLine();
        System.out.println("请输入子串:");
        String subStr = sc.nextLine();
        countSubString(str,subStr);
    }

    private static void countSubString(String str,String subStr) {
        int count = 0;
        for(int i = 0; i <= str.length() - subStr.length(); i++){
            if(subStr.equals(str.substring(i,subStr.length()+i))){
                count++;
            }
        }
        System.out.println("字符子串的个数为:"+count);
    }
}

2、测试结果:

"D:\Program Files\Java\jdk-9.0.4\bin\java.exe" "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA 2018.2.5\lib\idea_rt.jar=50307:D:\Program Files\JetBrains\IntelliJ IDEA 2018.2.5\bin" -Dfile.encoding=UTF-8 -classpath E:\Java练习\基础类型题\chap01\out\production\Java练习 demo15.Demo15
请输入字符串:
dhg34hgfdsg34hsdf345sdhj34sdh34hdfa34
请输入子串:
34
字符子串的个数为:6

 

 

你可能感兴趣的:(java初学者,习题,java)