1.有一個字符串,其中包含中文字符、英文字符和數字字符,請統計和打印出各個字符的個數。
Map接口定義的集合又稱查找表,用於存儲所謂“Key-Value”映射對。Key可以看成是Value的索引,作為Key的對象在集合中不可以重復。
import java.util.HashMap; import java.util.Map; public class Demo { public static void main(String[] args) throws Exception{ String content="中國ABCawpl8394么美國"; Map<Character,Integer> map=new HashMap(); char[] arryChar=content.toCharArray(); for(char c:arryChar){ if(map.containsKey(c)){ map.put(c, map.get(c)+1); }else{ map.put(c, 1); } } System.out.println(map); } }
2.有一個字符串,其中包含中文字符、英文字符和數字字符,請統計和打印出各個字符的個數
char 中 65 對應A 90 對應 Z 97 對應a 對應z 可以查看ASCII表
public static void main(String[] args) { String s = "aaaabbc中國1512"; int zh = 0 ; int en = 0; int num = 0; for(int i = 0; i< s.length() ;i++){ char c = s.charAt(i); if((c >= 'a' && c <= 'z')||(c >= 'A' && c <= 'Z')){ en++; }else if(c >= '0' && c <= '9'){ num++; }else{ zh++; } } System.out.println("中文個數" + zh); System.out.println("英文個數" + en); System.out.println("數字個數" + num); }