import java.util.Scanner;
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("请输入字符串");
String strIn= s.nextLine();
System.out.println("请输入子串");
String strCh = s.nextLine();
//判断该字串是否存在
boolean isCon=true;
if(!strIn.contains(strCh)){
isCon=false;
}
if(isCon){
System.out.print("包含该字串,");
int strCount=0; //统计字串个数的变量
while(true){
int pos = strIn.indexOf(strCh);
if(pos==-1)break; //跳出循环
strCount++;
strIn= strIn.substring(pos +strCh.length());
}
System.out.print("该字串出现的次数为:"+strCount);
}else{
System.out.println("不包含该字串");
}
}
Java——在一个字符串中查找一个子串,计算出来这个子串在字符串中出现的次数。
于 2018-07-16 15:36:06 首次发布