- import java.util.Scanner;
- public class StrStat
- {
- public static void main(String[] args)
- {
- String str = null;
- String subStr = null;
- int count = 0;
- do{
- System.out.println("#############################################");
- System.out.print("输入字符串:");
- str = getStr();
- if(str.equals("over")){
- System.out.println("谢谢使用");
- break;
- }
- System.out.print("再输入子串:");
- subStr = getStr();
- if(subStr.equals("over")){
- System.out.println("谢谢使用");
- break;
- }
- count = statStr(str,subStr);
- System.out.println("子串出现次数为 "+count);
- }while(true);
- }
- /**
- * 获取输入字符串
- */
- private static String getStr(){
- Scanner s = new Scanner(System.in);
- return s.nextLine();
- }
- /**
- * 统计子串个数
- */
- private static int statStr(String str,String subStr){
- //子串计数
- int subCount = 0;
- //下标记录
- int index = 0;
- //不断循环直到不能找到子串
- while((index = str.indexOf(subStr,index)) != -1){
- //下标移动
- index += subStr.length();
- //子串计数++
- subCount++;
- }
- return subCount;
- }
- }
复制代码 |