Java——在一個字串中查詢一個子串,計算出來這個子串在字串中出現的次數。
阿新 • • 發佈:2019-02-18
引入包:import java.util.Scanner;
main函式:
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();
//判斷該字串是否存在
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("不包含該字串");
}
}