Java在长字符串中查找短字符串的多种方法

Java在长字符串中查找短字符串的多种方法

方案一:
补充:在输入短字符串时,如果有空格,可以在比较前用 trim()方法截取前后空白

 /*该方法只适用于有特殊分割符号的字符串*/
        System.out.println("请输入字符串:");
        Scanner str1=new Scanner(System.in);
        String s=str1.nextLine();
        System.out.println("请输入第二个字符串:");
        Scanner str2=new Scanner(System.in);
        String  s2=str2.next();
        String[] i= s.split(" ");//对长字符串进行分割得到一个字符串数组
        int o=0;
        for (int j = 0; j 

方案二:

 //如果替换未造成字符串长度损失,该方法则不适用
        System.out.println("请输入一个长字符串:");
        Scanner str1 = new Scanner(System.in);
        String s = str1.nextLine();
        System.out.println("请输入短字符串:");
        String s1 = str1.nextLine();
        String s3 = s.replaceAll(s1, "0");//字符替换
        int b1 = s.length() - s3.length();//计算出s字符串损失的长度
        int b2 = b1 / (s1.length() - 1);//根据规律计算出s1字符串在s字符串中出现的次数
        System.out.println("次数为:"+b2);

方案三:

    //该方法适用于各种模式
        System.out.println("请输入一个长字符串:");
        Scanner str1 = new Scanner(System.in);
        String s = str1.nextLine();
        System.out.println("请输入短字符串:");
        String s1 = str1.nextLine();
        int c=0;
        for (int i = 0; i 

关注我,为您奉上更多有趣的方法。

你可能感兴趣的:(Java,java,字符串,算法)