/*
* 如何判斷一個字符串中某個字符出現的次數?
* 方法一:通過for循環去比對,count++
* 方法二:原來的長度減去將查找的字符替換為空后的長度即為某個字符出現的次數
* */
public class jishi4 {
public static void main(String[] args) {
//方法一:通過for循環去比對,count++
method01();
//方法二:原來的長度減去將查找的字符替換replace為空后的長度即為某個字符出現的次數
method02();
}
private static void method02() {
String oldStr="ABC123123ABC";
String searchChar = "B";
String newStr = oldStr.replace(searchChar, "");
System.out.println("字符"+searchChar+ "出現的次數為:" + (oldStr.length()-newStr.length()));
}
private static void method01() {
String str="abcABC";
char searchChar = 'B';
int count = 0;
char[] charArray = str.toCharArray();
for(char item : charArray){
if(item == searchChar){
count++;
}
}
System.out.println("字符" + searchChar + "出現的次數為:" + count);
}
}