A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

package it.may;

import java.util.Scanner;

/*
* 定义两个字符串:一大串s1,一小串s2;
* 使用indexOf(int a) + substring(int start,int end) 返回的是一个int值,故需要用int 类型来接收
* 统计次数:count++;
* 遍历循环
*                        
* */
public class StringDemo4 {
        public static void main(String[] args) {
                //字符串赋值,当然也可以键盘录入
               
                String s1 = "we";
                String s2 = "jawevahewellowowelordwewewe";
                /*
                 //键盘录入
                 System.out.println("请输入字符串:");
                 Scanner sc = new Scanner(System.in);
                 String s1 = sc.nextLine();
                 System.out.println("请输入字符串:");
                 String s2 = sc.nextLine();
                 * */
                 

                int count = getCount(s1, s2);
                System.out.println("count = " + count);

        }

        // 返回值:int;
        // 参数列表:String 大串 ,小串;
        public static int getCount(String s1, String s2) {

                // 在大串中查找小串一次;
                int count = 0;
                //假如用户输入的任意两个子字符串,那么将先判断那个是max,那个是min
                String max ="";
                String min ="";
                //int max = a>b?a:b; 通过字符串长度来判断那个是max,那个min
                max = s1.length()>s2.length()?s1:s2;
                min = (max == s1)?s2:s1;
                //返回min在max字符串中第一次出现的索引值
                int index = max.indexOf(min);
                //while循环中,可以判断“max还包含min吗?”,当然使用最多的是index=-1
                while (max.contains(min)) {
                        count++;
                        //让max每次都缩减到min出现后位置。
                        max = max.substring(index + min.length());
                         index = max.indexOf(min);

                }
                return count;

        }

}


2 个回复

倒序浏览
这个写的不错
回复 使用道具 举报

O(∩_∩)O谢谢:)
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马