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

/*
 * 需求:统计字符串中每个字母:
 * 说明:编写程序,提示用户输入一个字符串,
 * 然后统计字符串中每个字母出现的个数,忽略字母的大小写。
 * 
 * 原理:
 * 1.使用String类中的toLowerCase()方法,将字符串中的大写字母转换成小写形式。
 * 2.构造一个具有26个int值得数组ch ,每个元素记录一个字母出现的次数。
 * 	即,ch[0]记录a的个数,ch[1]记录b的个数。
 * 3.对字符中的每一个字符,判断其是否小写字母,如果是,则数组中的相应计数器加1.
 * 
 * */

package P0;
import javax.swing.JOptionPane;

public 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;
	}

}







 

 

「更多精彩内容请关注公众号geekymv,喜欢请分享给更多的朋友哦」

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值