Java笔记··By/蜜汁炒酸奶

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

本文提供三种方案,本质都是先将字符串转为数组:

  • String.charAt(index)
  • String.split(“”)
  • String.toCharArray()

具体如下:

	/**
	 * 通过String.charAt(index)获取字符串中的字符
	 * @param str
	 */
	public static void count(String str){
		Map<Character, Integer> map = new HashMap<Character, Integer>();
		int total = 0;
		Character tmp = null;
		for (int i=0;i<str.length(); i++) {
			tmp = str.charAt(i);
			total = 1;
			if (map.containsKey(tmp)) {
				total = map.get(tmp)+1;
			}
			map.put(tmp, total);
		}
		PrintUtill.printlnRule();
		PrintUtill.println(map);
	}

	/**
	 * String.charAt(index)的变种,将最后存储的Character类型转为String类型
	 * @param str
	 */
	public static void count2(String str){
		Map<String, Integer> map = new HashMap<String, Integer>();
		int total = 0;
		String tmp = null;

		String maxChar = str.charAt(0) + "";
		int maxToal = 1;

		for (int i=0;i<str.length(); i++) {
			tmp = str.charAt(i) + "";
			total = 1;
			if (map.containsKey(tmp)) {
				total = map.get(tmp)+1;
			}
			map.put(tmp, total);
			if (maxToal<total) {
				maxToal = total;
				maxChar = tmp;
			}
		}
		PrintUtill.printlnRule();
		PrintUtill.println(map);
		PrintUtill.println( "出现次数最多的字母是:" + maxChar + ",出现次数是:" + maxToal);
	}

	/**
	 * 通过String.split("")将字符串直接切割成字符串数组
	 * @param str
	 */
	public static void count3(String str){
		Map<String, Integer> map = new HashMap<String, Integer>();
		int total = 0;
		String[] myStrs = str.split("");
		String tmp = null;
		for (int i=0;i<myStrs.length; i++) {
			tmp = myStrs[i];
			total = 1;
			if (map.containsKey(tmp)) {
				total = map.get(tmp)+1;
			}
			map.put(tmp, total);
		}
		PrintUtill.printlnRule();
		PrintUtill.println(map);
	}

	/**
	 * 通过String.toCharArray()将字符串转为char数组
	 * @param str
	 */
	public static void count4(String str){
		Map<String, Integer> map = new HashMap<String, Integer>();
		int total = 0;
		char[] myStrs = str.toCharArray();
		String tmp = null;
		for (int i=0;i<myStrs.length; i++) {
			tmp = myStrs[i] + "";
			total = 1;
			if (map.containsKey(tmp)) {
				total = map.get(tmp)+1;
			}
			map.put(tmp, total);
		}
		PrintUtill.printlnRule();
		PrintUtill.println(map);
	}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
预览
Loading comments...
0 条评论

暂无数据

example
预览