问题
User will enter a String, For instance if the user enters YYYCZZZZGG: Program will evaluate the frequency of characters in the string. For YYYCZZZZGG string, C is seen only for 1, G is repeated 2, Y has a frequency of 3, and Z’s frequency is 4.
after finding number of each letter how can I draw a bar graph using the numbers of the programs output?
回答1:
Try this:
public static void main(String[] args) {
String input = "YYYCZZZZGG";
Map<Character, Integer> map = new HashMap<Character, Integer>(); // Map
// to store character and its frequency.
for (int i = 0; i < input.length(); i++) {
Integer count = map.get(input.charAt(i)); // if not in map
if (count == null)
map.put(input.charAt(i), 1);
else
map.put(input.charAt(i), count + 1);
}
System.out.println(map);
}
Output:
{G=2, C=1, Y=3, Z=4}
回答2:
Use Apache StringUtils
:
It contains a method that can be used like StringUtils.countMatches("YYYCZZZZGG", "Y");
回答3:
int count = StringUtils.countMatches("YYYCZZZZGG", "C");
Just a matter of copy paste from Java: How do I count the number of occurrences of a char in a String?
回答4:
You can do it like this:
String s = "YYYCZZZZGG";
Map<Character, Float> m = new TreeMap<Character, Float>();
for (char c : s.toCharArray()) {
if (m.containsKey(c))
m.put(c, m.get(c) + 1);
else
m.put(c, 1f);
}
for (char c : s.toCharArray()) {
float freq = m.get(c) / s.length();
System.out.println(c + " " + freq);
}
Or you can use StringUtils class like:
System.out.println("The occurrence of Z is "+StringUtils.countMatches(s, "C"));
回答5:
String str="YYYCZZZZGG";
Map<Character,Integer> map=new HashMap<Character,Integer>();
for (char c : str.toCharArray()) {
if(map.containsKey(c))
{
int i=map.get(c);
i++;
map.put(c, i);
}
else
{
map.put(c, 0);
}
}
for(Map.Entry<Character, Integer> entry:map.entrySet())
{
char c=entry.getKey();
int count=entry.getValue();
}
来源:https://stackoverflow.com/questions/16296105/find-the-number-of-every-letters-in-a-word