给出一个字母字符串,统计字符串中每个字母出现的次数

来源:互联网 发布:java中有哪些方法 编辑:程序博客网 时间:2024/05/16 10:43
  1. /* 
  2.  * 需求:统计字符串中每个字母: 
  3.  * 说明:编写程序,提示用户输入一个字符串, 
  4.  * 然后统计字符串中每个字母出现的个数,忽略字母的大小写。 
  5.  *  
  6.  * 原理: 
  7.  * 1.使用String类中的toLowerCase()方法,将字符串中的大写字母转换成小写形式。 
  8.  * 2.构造一个具有26个int值得数组ch ,每个元素记录一个字母出现的次数。 
  9.  *  即,ch[0]记录a的个数,ch[1]记录b的个数。 
  10.  * 3.对字符中的每一个字符,判断其是否小写字母,如果是,则数组中的相应计数器加1. 
  11.  *  
  12.  * */  
  1. ublic class CountEachLetter {  
  2.   
  3.     /** 
  4.      * @param args 
  5.      */  
  6.     public static void main(String[] args) {  
  7.         // TODO Auto-generated method stub  
  8.           
  9.         String str = JOptionPane.showInputDialog("Please Enter a string: ");  
  10.           
  11.         int[] counts = countLetters(str.toLowerCase());  
  12.           
  13.         String out = "";  
  14.         for(int i=0;i<counts.length;i++)  
  15.         {  
  16.             if(counts[i]!=0)  
  17. //              out += (char)('a'+i)+"  appears"+counts[i]+((counts[i]==1)?"time\n":"times\n");  
  18.                 out +=(char)('a'+i)+":出现了"+counts[i]+"次.\n";  
  19.         }  
  20.           
  21.         JOptionPane.showMessageDialog(null, out);  
  22.   
  23.     }  
  24.       
  25.     public static int[] countLetters(String s)  
  26.     {  
  27.         int[] ch = new int[26];  
  28.         for(int i=0;i<s.length();i++)  
  29.         {  
  30.             if(Character.isLowerCase(s.charAt(i)))  
  31.                 ch[s.charAt(i)-'a']++;//  
  32.         }  
  33.           
  34.         return ch;  
  35.     }  
  36.   
  37. }  

0 0
原创粉丝点击