- /*
- * 需求:统计字符串中每个字母:
- * 说明:编写程序,提示用户输入一个字符串,
- * 然后统计字符串中每个字母出现的个数,忽略字母的大小写。
- *
- * 原理:
- * 1.使用String类中的toLowerCase()方法,将字符串中的大写字母转换成小写形式。
- * 2.构造一个具有26个int值得数组ch ,每个元素记录一个字母出现的次数。
- * 即,ch[0]记录a的个数,ch[1]记录b的个数。
- * 3.对字符中的每一个字符,判断其是否小写字母,如果是,则数组中的相应计数器加1.
- *
- * */
- ublic class CountEachLetter {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- String str = JOptionPane.showInputDialog("Please Enter a string: ");
- int[] counts = countLetters(str.toLowerCase());
- String out = "";
- for(int i=0;i<counts.length;i++)
- {
- if(counts[i]!=0)
- // out += (char)('a'+i)+" appears"+counts[i]+((counts[i]==1)?"time\n":"times\n");
- out +=(char)('a'+i)+":出现了"+counts[i]+"次.\n";
- }
- JOptionPane.showMessageDialog(null, out);
- }
- public static int[] countLetters(String s)
- {
- int[] ch = new int[26];
- for(int i=0;i<s.length();i++)
- {
- if(Character.isLowerCase(s.charAt(i)))
- ch[s.charAt(i)-'a']++;//
- }
- return ch;
- }
- }