統計字符在字符串中出現的次數
方式1:在map集合中進行if-else判斷
public class Demo01 {
public static void main(String[] args) {
//統計字符在字符串中出現的次數;
String str = "qwerqqqqqqweqweeeewqq";
Map<Character, Integer> map = new HashMap<>();
//對字符串進行遍歷;
for (int i = 0; i < str.length(); i++) {
// charAt:根據索引尋找字符
char c = str.charAt(i);
//判斷是否包含指定的字符;
if (!map.containsKey(c)) {
//若不包含就存入map中;
map.put(c, 1);
} else {
//若包含則加出現次數+1;
map.put(c, map.get(c) + 1);
}
}
System.out.println(map);
//輸出結果:{q=10, r=1, e=6, w=4}
}
}
方式2:通過 字母的ascll碼相減,統計次數
public class Demo01 {
public static void main(String[] args) {
//統計字符在字符串中出現的次數;
String str = "qwerqqqqqqweqweeeewqq";
//方式2:
//由於每個字母都有着對應的ascll碼;創建長度為26的數組;
int[] counts = new int[26];
//對字符串進行遍歷;
for (int i = 0; i < str.length(); i++) {
// charAt:根據索引尋找字符
char c = str.charAt(i);
//讓拿到的每個字母;去減第一個字母的值;(實際上有隱式的ascll碼相減);
//減出來的值就相當於拿到一次;每減一次就加一次,最終會把疊加的次數計入數組;
counts[c - 'a']++;
}
//遍歷數組;
for (int array : counts) {
System.out.print(array + " ");
}
//計算結果:0 0 0 0 6 0 0 0 0 0 0 0 0 0 0 0 10 1 0 0 0 0 4 0 0 0
}
}