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 <i.length ; j++) {
      if (s2.equals(i[j])==true){//对字符数组进行遍历比较
        o++;
      }
    }
    System.out.println("次数为:"+o);
  }

方案二:

 //如果替换未造成字符串长度损失,该方法则不适用
    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 <s.length()-s1.length() ; i++) {
      if (s1.equals(s.substring(i,i+s1.length()))){/*字符串比较,对长字符串进行截取,之后用截取得到的字符串与短字符串进行比较*/
        ++c;
      }
    }
    System.out.println("次数为: " + c);