英特尔中国_求一个字符串中某个字符的个数最多的那个字符。

 例如输入:This is a string test 其中t字符的个数最多。

package com.Yter;
import java.util.*;
/*
 * This is a string test
 * t的个数为4
 */
public class Yter_1 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		String str = sc.nextLine().trim();
		String str2="";
        //首先将大写转换成小写
		for(int j=0;j<str.length();j++){
			char ch1 = ' ';
			if(str.charAt(j)!=' '){
				 ch1=Character.toLowerCase(str.charAt(j));
			}else{
				 ch1=str.charAt(j);
			}
			str2+=ch1;
		}
		System.out.println(str2);
		Map<Character,Integer> map = new HashMap<Character,Integer>();
        //用Hashmap对每个字符的统计,键为字符,值为该字符的个数,注意,这里会包含空格的个数。
		for(int i=0;i<str2.length();i++){
			char ch = str2.charAt(i);
			if(map.get(ch)!=null){				
				map.put(ch, map.get(ch)+1);
			}else{
				map.put(ch, 1);
			}
		}
		int max=0;
		char maxkey=' ';
        //对map进行遍历,通过entry.getKey()得到键,通过entry.getValue()得到值。在这过程中得到 
         //最大的那个值和键
		for(Map.Entry entry:map.entrySet()){
			if((Integer)entry.getValue()>max && (Character)entry.getKey()!=' '){
				max = (Integer) entry.getValue();
				maxkey = (Character)entry.getKey();
			}			
			System.out.println(entry.getKey()+":"+entry.getValue());
		}
		System.out.println("最终结果为:");
		System.out.println(max);
		System.out.println(maxkey);
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_39912556/article/details/82468930