import java.util.Scanner;
/**
* 編寫一個方法,輸出在一個字符串中,指定字符串出現的次數
提示:
方法一:使用indexOf和subString方法,循環判斷並截取
方法二:使用replace方法將字符串替換爲空,然後求長度
* @author 萬星明
* @version 1.0
* @time
*/
public class Work4 {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("請輸入原字符串:");
String st = sc.next();
System.out.println("請輸入指定字符串:");
String M = sc.next();
way1(st,M);
way2(st,M);
}
/**
* 方法一:使用indexOf和subString方法,循環判斷並截取
*/
public static void way1(String st,String M) {
int count = 0;
while(st.indexOf(M)>=0) {
st=st.substring(st.indexOf(M)+M.length());
count++;
}
System.out.println("指定字符串在原字符串中出現:"+count+"次");
}
/**
* 方法二:使用replace方法將字符串替換爲空,然後求長度
*/
public static void way2(String st,String M) {
int count = (st.length()-st.replace(M, "").length())/M.length();
System.out.println("指定字符串在原字符串中出現:"+count+"次");
}
}