Day_09【常用API】扩展案例2_测试小字符串在大字符串中出现的次数

分析以下需求,并用代码实现

  •   1.键盘录入一个大字符串,再录入一个小字符串
      2.统计小字符串在大字符串中出现的次数
      3.代码运行打印格式:
      	请输入大字符串: woaiheima,heimabutongyubaima,wulunheimahaishibaima,zhaodaogongzuojiushihaoma
      	请输入小字符串:heima
      	控制台输出:小字符串heima
      	在大字符串woaiheima,heimabutongyubaima,wulunheimahaishibaima,zhaodaogongzuojiushihaoma中共出现3次
    
package com.itheima2;

import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("请输入一个大字符串:");
		String bigstr = sc.nextLine();
		
		System.out.println("请输入一个小字符串:");
		String smallstr = sc.nextLine();
		
		//调用方法
		int count = getCount(bigstr, smallstr);
		
		//输出
		System.out.println("在大字符串"+bigstr+"中,小字符串"+smallstr+"一共出现了"+count+"次");
	}

	/*
	 * 统计小字符串在大字符串中出现的次数
	 * 		返回值类型:int count
	 * 		参数列表:String bigstr,String smallstr
	 */
	
	public static int getCount(String bigstr,String smallstr) {
		int count = 0;
		int index = 0;
		/*public int indexOf​(String str,int fromIndex)
		该方法作用:从fromIndex位置开始查找,字符串str第一次出现的位置;若没找到,返回-1
		*/
		while((index = bigstr.indexOf(smallstr, index)) != -1) {
			index++;
			count++;
		}
		return count;
	}
}

控制台输出内容

控制台输出内容

原文地址:https://www.cnblogs.com/zzzsw0412/p/12772540.html