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

  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. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值