统计文章中的字符串(一)

问题描述:

文章的字符统计
HEFEI-At age four, Ji Tingqiao could remember the names of all the bones of a skeleton. In primary school, he could understand heavy ancient Chinese classics. At 15, this September, he started university.
Across China, gifted students over the past 40 years have been enrolled in a special program set up in the University of Science and Technology of China.
统计上面这篇文章,每个英文字符出现的次数

思路:

 最近学习了map类的HashMaple类,因为字符串是无序的,所以想利用利用映射关系,将映射相同的KEY对应的值统计出来;

由于是要求统计英文字符,所以在统计(参数传递)之前,将字符串中的所有大小写英文字符分割出来;

代码测试

public class tongji1 {
public static void Hashway ( String str) {
char[] a=str.toCharArray();
HashMap <Character,Integer> s=new HashMap();
for(char c: a) {
    if(!s.containsKey(c)) {
        s.put(c, 1);
    }else {
        s.put(c, s.get(c)+1);
    }
}
    for(Character key:s.keySet())
System.out.println(key+"在文章中出现的次数"+s.get(key));
}
public static void main(String[] args) {
    String str="HEFEI-At age four, Ji Tingqiao could remember the names of all the bones of a skeleton. In primary school, he could understand heavy ancient Chinese classics. At 15, this September, he started university.\r\n" +
        "Across China, gifted students over the past 40 years have been enrolled in a special program set up in the University of Science and Technology of China." ;
     String astr=null;
     char []b=str.toCharArray();
      for(int i=0;i<str.length();i++) {
        if((b[i]>='a'&&b[i]<='z')||(b[i]>='A'&&b[i]<='Z')) {
               astr+=b[i];
                 }
            }
         Hashway(astr);   //调用方法
    
}

}

猜你喜欢

转载自www.cnblogs.com/nulinulizainuli/p/10526724.html
今日推荐