1.鍵盤錄入一個大字符串,再錄入一個小字符串
2.統計小字符串在大字符串中出現的次數
3.代碼運行打印格式:
請輸入大字符串:woaiheima,heimabutongyubaima,wulunheimahaishibaima,zhaodaogongzuojiushihaoma
請輸入小字符串:heima
控制檯輸出:小字符串heima,在大字符串中共出現3次
public class Exam03 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = "woaiheima,heimabutongyubaima,wulunheimahaishibaima,zhaodaogongzuojiushihaoma";
String sub = "heima";
int filter = filter(s, sub);
System.out.println(sub+"在大字符串中出現了"+filter+"次");
}
public static int filter(String s,String sub){
int old_length=s.length();
String replace="";
if (s.contains(sub)){
replace = s.replace(sub, "");//將需要查找的字符串替換爲空
}
int new_length= replace.length();//用原來字符串的長度去減替換過的字符串就是該字符串中字符出現的次數
int count=(old_length-new_length)/(sub.length());//因爲是字符串中字符出現的次數,所以要除以字符串你的長度最後就是字符串在另一個字符串中出現的次數
return count;
}
}
此方法跟前面統計字符串中每個字符出現的個數大致相同,如果想保留原來的字符串就在方法體首部將原來的字符串賦給一箇中間變量.統計完再將他賦值回去.
下面的方法是利用了String裏面的indexOf方法.通過判斷返回的值不等於-1開始循環.indexOf是返回指定字符串在原來的字符串出現第一次的位置索引.然後下次循環就從這一次的下一次開始循環.每次得到索引值時計數器加一.
/**
* .獲取一個字符在一個字符串中出現的次數,
* 比如:String st = "adfdfsfksdfsdjfhsjdfhsfkdfgjdfkgljlds";
* 字符‘f’在字符串st中出現的次數
*/
public class Assign03 {
public static void main(String[] args) {
String st = "adfdfsfksdfsdjfhsjdfhsfkdfgjdfkgljlds";
int count=pinrtCount(st, "f");
System.out.println("出現了"+count+"次");
}
public static int pinrtCount(String string, String subString) {
int index=0;
int count=0;
while ((index = string.indexOf(subString,index)) !=-1){
//在循環控制的條件中將獲得的索引值賦給index,不等於-1是因爲.在JDK中規定了indexOf查找不到子字符串時就返回-1.在我們這裏也就是跳出循環的意思
index++;//得到索引後,從本位置開始進行下一次循環,所以字符串的索引加一
count++;//計數器統計出現的次數
}
return count;
}
}
下面是我們老師教的方法.可以自行參考.方法不在多,自己掌握就好.
public class Test {
public static void main(String[] args) {
String str1 = "aaaa";
String str2 = "aa";
int count=0;
while (true) {
int index = str1.indexOf(str2);//0
if (index != -1) {
count++;
// str1 = str1.substring(index+str2.length()); //每次截取不包含出現過的字符
str1 = str1.substring(index+1);//一個一個字符往後計算
} else {
break;
}
}
System.out.println(count);
}
public static void ss(String str1, String str2) {
int count = 0;
while (true) {
int i = str1.indexOf(str2);
if (i == -1) {
break;
} else {
count++;
str1 = str1.substring(i+str2.length());
}
}
System.out.println(count);
}
}