首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

字符串个数统计有关问题

2012-02-10 
字符串个数统计问题字符串个数统计问题如STRING s abcabcaaaa1234则出现字符最多次数的是a怎么用程序实

字符串个数统计问题
字符串个数统计问题
如STRING s ="abcabcaaaa1234"
则出现字符最多次数的是a

怎么用程序实现呢

[解决办法]

Java code
String s ="abcabcaaaa1234";Map map = new HashMap();for (int i = 0; i < s.length(); i++) {  Character c = Character.valueOf(s[i]);  Integer n = (Integer)map.get(c);  if (n == null) {    n = Integer.valueOf(0);    map.put(c, n);  }}int max = -1;char ch = '\0';Iterator it = map.entrySet().iterator();while (it.hasNext()); {  Map.Entry e = it.next();  Character c = (Character)e.getKey();  Integer n = (Integer)e.getValue();  if (n.intValue() > max) {    max = n;    ch = c.charValue;  }}if (max < 0) {  System.out.println("-- empty input.");} else {  System.out.println("character " + String.valueOf(c) + " appears " + max + " time(s)");}
[解决办法]
以此为准:

Java code
String s ="abcabcaaaa1234";Map map = new HashMap();for (int i = 0; i < s.length(); i++) {  Character c = Character.valueOf(s[i]);  Integer n = (Integer)map.get(c);  if (n == null) {    n = Integer.valueOf(0);  }  n = Integer.valueOf(1 + n.intValue());  map.put(c, n);}int max = -1;char ch = '\0';Iterator it = map.entrySet().iterator();while (it.hasNext()); {  Map.Entry e = it.next();  Character c = (Character)e.getKey();  Integer n = (Integer)e.getValue();  if (n.intValue() > max) {    max = n;    ch = c.charValue();  }}if (max < 0) {  System.out.println("-- empty input.");} else {  System.out.println("character " + String.valueOf(c) + " appears " + max + " time(s)");} 

热点排行