zoukankan      html  css  js  c++  java
  • 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;
    	}
    }
    
    

    控制台输出内容

    控制台输出内容

  • 相关阅读:
    抽象类中可以存在的成员
    读暗时间后感
    使用正则表达式限制QLineEdit不能输入大于某个整数
    QSharedMemory 使用
    BUUCTF-misc九连环 详解
    BUUCTF-数据包中的线索 1
    BUUCTF-Windows系统密码
    [CISCN2019 华北赛区 Day2 Web1]Hack World 1详解
    [ZJCTF 2019]NiZhuanSiWei 1详解
    BUUCTF [BJDCTF2020]Easy MD5 详解
  • 原文地址:https://www.cnblogs.com/zzzsw0412/p/12772540.html
Copyright © 2011-2022 走看看