一组字符,计算各字符出现的次数。手写代码。

 首先上代码:如下

第一种(在控制台上输入): 

public class zifuTow {
	public static void main(String[] args) {
		Scanner scan=new Scanner(System.in);
		System.out.println("请输入一组串字符串");
		String str=scan.nextLine();
		str=str.replaceAll("[\\W]", "");
		Map<Character,Integer> map = new HashMap<Character,Integer>();
		for(int i=0;i<str.length();i++){
			if(map.containsKey(str.charAt(i))){
				map.put(str.charAt(i), map.get(str.charAt(i))+1);
			}else{
				map.put(str.charAt(i), 1);
			}
		}
		System.out.println(map);
		scan.close();
	}

}

运行结果如下:

因为我们在代码中写了Scanner,Scanner是最简单的数据输入。下面随便写一组字符串:afaf4aw5f15a65f1ds5vawfdca5sd1sa5df1。

运行结果:

第二种(直接在代码上面写一组字符串,程序运行时直接运行): 

public class zifuOne {
	public static void main(String[] args) {
		String str="sdnasjhdasdaksnfcjdshdfufhaosinfdsjncxkjz";
		Map<Character,Integer> map=new HashMap<Character,Integer>();
		char[] arr=str.toCharArray();
		
		for(char ch:arr){
			if(map.containsKey(ch)){
				Integer old=map.get(ch);
				map.put(ch, old+1);
			}else{
				map.put(ch, 1);
			}
		}
		System.out.println(map);
	}

}

运行结果如下:

第二种方法的代码中没有Scanner,所以程序运行的时候直接运行,是很方便,但是如果用在实际项目当中,用户体验感不好,因为第二种的程序是写死了的字符串,怎么可能让每个用户都如意呢?

第二种只是适合初学者的理解,再而进入第一种,本人也强烈推荐使用第一种,用户爱输入什么字符串,我们照样都能满足用户的需求。

猜你喜欢

转载自blog.csdn.net/qq_41879385/article/details/81229164