2012-01-06 36 views

回答

1

我会建议使用从字符映射计数和遍历字符数组添加到地图或当你沿着

2

科瑞去计数使用键作为字符和整数作为值的HashMap。

HashMap<Character, Integer> hm = new HashMap<Character, Integer>() 
for (int i = 0; i < str.length; i++) { 
    if (hm.get(str.charAt(i))) { 
     int temp = hm.get(str.charAt(i)); 
     hm.put(str.charAt(i), ++temp); 
    } else { 
     hm.put(str.charAt(i), 1); 
    } 
} 
0

你可以解析并创建一个Map<Character, Integer>使得整数(在地图中值)代表了多少次的字符Ç(在地图上的键)字符串中出现。

0
public static Map<Character, Integer> count(String s) { 
    Map<Character, Integer> result = new HashMap<Character,Integer>(); 
    for (int i = 0; i < s.length(); ++i) { 
    char c = s.charAt(i); 
    Integer n = result.get(c); 
    result.put(c, n == null ? 1 : n + 1); 
    } 

    return result; 
} 
1
Map<Character, Integer> chars = new HashMap<Character, Integer>(); 
for (int i = 0; i < str.length; i++) { 
    char c = str.charAt(i); 

    Integer count = chars.get(c); 
    if (count == null) { 
     chars.put(c, 1); 
    } else { 
     chars.put(c, count + 1); 
    } 
} 
+0

由于这是功课,而且OP没有表现出任何努力,所以将他/她指向正确的方向并不比为他们做这件事更好吗? – 2012-01-06 16:36:47

1

,我在过去做一个简单的,但直观的方式是投作为字符整数,然后只用一个数组。使用Map是一种更好的方法,但这听起来像是一个家庭作业问题,对于初学者来说,使用cast和一个数组对于一个初学者来说更合乎逻辑(imo)。

int counts[] = new int[26]; 
String s = 'stackoverflow'; 
s = s.toLowerCase(); 
for (int i = 0; i < s.length(); i++) { 
    int val = (int)(s.charAt(i)) - 97; 
    counts[val]++; 
} 
0
String input = "stackoverflow"; 

// desired output: s:1 t:1 a:1 c:1 k:1 o:2 v:1 e:1 r:1 f:1 l:1 o:1 w:1 
Map<Character,Integer> counts = new HashMap<Character, Integer> 
(Math.min(input.length(),Character.MAX_VALUE)/2); 
char ch; 
for (int i=0; i<input.length(); ++i) 
{ 
    ch = input.charAt(i); 
    if (!counts.containsKey(ch)) { counts.put(ch,0); } 
    counts.put(ch, counts.get(ch)+1); 
} 

for (Map.Entry<Character,Integer> entry : counts.entrySet()) 
{ 
    out.print(entry.getKey()); 
    out.print(":"); 
    out.print(entry.getValue()); 
    out.print(" "); 
} 
3

Guava来救援!我简直不敢相信,这是一个Java单线程!

Multiset<Character> distintCharsAndCount = HashMultiset.create(
    Chars.asList("ssssssssstackoverflow".toCharArray()) 
); 

Chars.asList帮助我们将字符串转换为非基元的真实集合。 MultiSets是你所追求的完美结构:它是一个保持不同元素的集合,但也保持集合中出现的次数。

访问这样说:

int sCount = distintCharsAndCount.count('s'); //sets it to 9 
相关问题