如:s1,s2是兩個字元串,s1="abcdefab" s2="ab" 求字元串s2在s1中共出現的次數:
這裡我給大家介紹兩種方法
一、循環截取法
使用到的是String類中的subString(int beginIndex)方法、indexOf(String str)方法和length( )方法
//1.循環截取法
String s1="abcdefghab";
String s2="ab";
int count=0;
while(s1.indexOf(s2)!=-1){//s1.indexOf(s2)!=1說明s1中存在s2
s1=s1.substring(s1.indexOf(s2)+s2.length());//截取的起始位置
count++;
}
System.out.println("指定字元串在原字元串中共出現:"+count+"次");
二、替換求長法
使用String類中的replace(CharSequence target, CharSequence replacement)方法和length()方法
//2.替換求長法
String s1="abcdefghab";
String s2="ab";
int count=(s1.length()-s1.replace(s2,"").length())/s2.length();//s1.replace(s2,"").length()為替換後所得的字元串的長度
System.out.println("指定字元串在原字元串中共出現"+count+"次");
************************************************************************************
有問題聯系我,v.x:intboy520
***********************************************************************************