源代碼:
//java中判斷一個字符出現的次數
//在下面字符串中查找有幾個啊
public static void testFindChar(){
String str = "啊!我愛你中國!啊,我愛你故鄉";
//存放每個字符的數組
String [] strs = new String[str.length()];
//計數該字符出現了多少次
int count = 0;
//先把字符串轉換成數組
for(int i = 0;i<strs.length;i++){
strs[i] = str.substring(i,i+1);
}
//挨個字符進行查找,查找到之后count++
for(int i = 0;i<strs.length;i++){
if(strs[i].equals("啊")){
count++;
}
}
System.out.println("一共有"+count+"個啊");
}
運行結果如圖所示:
歡迎關注公眾號雄雄的小課堂: