java中输出一个字符串中出现次数最多的字符以及次数

  • 1 先把字符串转化为数组 .toCharArray
  • 2 定义一个数组count[i] 存取每个字符 以及数量 count[i]++
  • 3 计算每个字符 以及值
  • 4 取count的最大值
public class MaxString {

	public static void main(String[] args) {
		String s="aaahssjshsssssshwws123222";
		// 转化为字符数组。
		char[] c=s.toCharArray();
		// 定义一个数组存次数
		int [] count=new int[c.length];
		
		//把每个对应的值以及次数存下来
		for(int i=0;i<=c.length-1;i++)
		{
			char mid=c[i];
		    for(int j=0;j<=c.length-1;j++)
		    {
		    	if(mid==c[j])
		    	count[i]++;
		    }				
		}
		// 取出count数组的最大值,并且得到下标
		int index=0;
		int max=0;

		for(int i=0;i<=c.length-1;i++)
		{
			if(max<=count[i])
			{
				max=count[i];
				index=i;
			}			

		}
		
		System.out.println("出现最多的字符是:"+c[index]+"出现最多的次数是:"+count[index]);
				
		

	}

}

猜你喜欢

转载自blog.csdn.net/weixin_43251783/article/details/83542618
今日推荐