Java 找出一个单词中每个字母的数目
用户将输入一个字符串, 例如,如果用户输入YYYYCZZGG: 程序将评估字符串中字符的频率。 对于YYYYCZZGG字符串,C仅在1中显示,G重复2,Y的频率为3,Z的频率为4 找到每个字母的编号后,如何使用程序输出的编号绘制条形图Java 找出一个单词中每个字母的数目,java,string,bar-chart,Java,String,Bar Chart,用户将输入一个字符串, 例如,如果用户输入YYYYCZZGG: 程序将评估字符串中字符的频率。 对于YYYYCZZGG字符串,C仅在1中显示,G重复2,Y的频率为3,Z的频率为4 找到每个字母的编号后,如何使用程序输出的编号绘制条形图 int count = StringUtils.countMatches("YYYCZZZZGG", "C"); 只需从String str=“yyyczzzgg”复制粘贴即可; Map Map=newhashmap(); for(字符c:str.toCharA
int count = StringUtils.countMatches("YYYCZZZZGG", "C");
只需从String str=“yyyczzzgg”复制粘贴即可;
Map Map=newhashmap();
for(字符c:str.toCharArray()){
if(图c)
{
int i=map.get(c);
i++;
图.put(c,i);
}
其他的
{
map.put(c,0);
}
}
对于(Map.Entry:Map.entrySet())
{
char c=entry.getKey();
int count=entry.getValue();
}
您可以这样做:
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);
}
使用Apache
StringUtils
:
它包含一个可以使用的方法,如StringUtils.countMatches(“yyyczzzgg”,“Y”)代码>尝试以下操作:
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);
}
“用户将输入一个字符串,…程序将评估频率”程序员将显示一些努力..如果您同意N阶解决方案,只需检查所有字母,然后创建一个类似于M['C']=M['C']的映射+这些:谢谢你的回答,有没有办法把它转换成acm.jar包
System.out.println("The occurrence of Z is "+StringUtils.countMatches(s, "C"));
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);
}
{G=2, C=1, Y=3, Z=4}