給定一個包含各種字符的字符串,打印出其中字母和其出現的次數。
實現原理:
1. 利用正則匹配去除非字母字符。
2. 將字母為鍵,出現次數為值存入map。
3. 掃描字符串,若字母已存在於map中,值加1.
4. 打印map。
public static void count(String input) {
//?表示非貪婪匹配,i表示忽略大小寫,[^a-z]匹配所有非a-z范圍類字符。 String regex = "(?i)[^a-z]"; String result = input.replaceAll (regex, ""); System.out.println (result); HashMap<String, Integer> map = new HashMap<String, Integer> (); for ( int i = 0; i < result.length (); i++ ) { String one = result.charAt (i) + ""; if (null == map.get (one)) { //新字符,存入map,值為1 map.put (one, 1); } else { //已存在,值加一 map.put (one, map.get (one) + 1); } } System.out.println (map); }
測試代碼:
public static void main ( String args[] ) { String input = "016a 8b9c213d20df0G9E"; CountLetters test= new CountLetters(); test.countAlphabet(input); }
返回結果:
abcddfGE
{f=1, E=1, d=2, G=1, b=1, c=1, a=1}