gpt4 book ai didi

java - java获取字符串中每个字符的相对频率

转载 作者:行者123 更新时间:2023-12-01 15:22:45 25 4
gpt4 key购买 nike

我想获得字符串中每个唯一字符的平均值。我这里有一个例子,因为它会更容易说明。

字符串:

The big brown fox

每个字符(包括空格)的平均值:

T = 1/17 = .058
h = 1/17 = .058
e = 1/17 = .058
' '= 3/17 = .176
b = 2/17 = .117
i = 1/17 = .058
g = 1/17 = .058
r = 1/17 = .058
o = 2/17 = .117
w = 1/17 = .058
n = 1/17 = .058
f = 1/17 = .058
x = 1/17 = .058

到目前为止我所有的尝试都失败了,我想我的大脑现在不工作了。我该如何编码?任何帮助或意见将不胜感激。

我有这个代码作为解决方案。当我将代码复制粘贴到堆栈中时,我突然想到了这一点。我希望这不是重新发帖,因为我几分钟前刚刚回答了同样的问题,但它没有出现。

 Map<String, Integer> storeCharCount = new HashMap<String, Integer>();

String a = "The big brown fox";


for (int x=0; x<a.length(); x++){
char getChar = a.charAt(x);
String convGetChar = Character.toString(getChar);

Integer countChar = storeCharCount.get(convGetChar);
storeCharCount.put(convGetChar, (countChar==null?countChar=1:countChar+1));

}
System.out.println("Map: "+ storeCharCount);
double RelFrequency = 0;
for (Map.Entry<String, Integer> getValue: storeCharCount.entrySet()){

RelFrequency = (double)(getValue.getValue())/(a.length());
System.out.println("Character "+getValue.getKey() +" Relative Frequency: "+RelFrequency);

}

这是输出

Map: {f=1, g=1,  =3, e=1, b=2, n=1, o=2, h=1, i=1, w=1, T=1, r=1, x=1}
Character f Relative Frequency: 0.058823529411764705
Character g Relative Frequency: 0.058823529411764705
Character Relative Frequency: 0.17647058823529413
Character e Relative Frequency: 0.058823529411764705
Character b Relative Frequency: 0.11764705882352941
Character n Relative Frequency: 0.058823529411764705
Character o Relative Frequency: 0.11764705882352941
Character h Relative Frequency: 0.058823529411764705
Character i Relative Frequency: 0.058823529411764705
Character w Relative Frequency: 0.058823529411764705
Character T Relative Frequency: 0.058823529411764705
Character r Relative Frequency: 0.058823529411764705
Character x Relative Frequency: 0.058823529411764705

最佳答案

这是我的建议。首先迭代字符串中的每个字符,如果找到则更新频率,否则添加 1。然后再次迭代以打印结果:

        String s = "The big brown fox";
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);
}

关于java - java获取字符串中每个字符的相对频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10650594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com