package demo1;
/**
*
*@author 高碩
*計算子串出現的次數
*1.indexof(String str,int fromIndex)返回指定字符串在此字符串中第一次出現處的索引
*2.計數count++
*3.fromIndex加上字符串的長度,尋找下處的位置
*4.停止條件,indexof返回-1
*/
import java.io.*;
import java.util.Scanner;
public class Main{
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//第一個
Scanner in = new Scanner(System.in);// 調用鍵盤輸入API
String str =in.nextLine();//定義String 類型的變量str接住用戶輸入的字符串
String substr =in.nextLine();//定義String 類型的變量substr接住用戶輸入的字符串
findCount(str,substr);
}
public static void findCount(String src, String des) {
int index = 0;
int count = 0;
//indexof(String str,int fromIndex)返回指定字符串在此字符串中第一次出現處的索引
while ((index = src.indexOf(des, index)) != -1) {
count++;
index = index + des.length();
}
System.out.println(des + "出現了 " + count + " 次");
}
}
計算一個字符串在另一個字符串中出現的次數
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.