字符串数组中字符出现的平均值

时间:2015-06-11 06:08:04

标签: java

我想计算字符串中字符出现的平均值,例如,如果我传递一个数组[" hie"," raisin"," critical" ],我传递一个目标,然后我的方法应该返回1.6。我如何在java中执行此操作

from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
links = [tag for tag in soup.findAll('a') if tag.has_attr('href')]

3 个答案:

答案 0 :(得分:3)

我的实施:

String[]  array = new String[]{"hie","raisin","critical"};
Double[] occs = new Double[256];
for(int i = 0; i < occs.length; i++) {
    occs[i] = 0.;
}
for(String str: array) {
    for(char ch: str.toCharArray()) {
        occs[ch]++;
    }
}
System.out.println(occs['i']/array.length); // 1.66...
System.out.println(occs['r']/array.length); // 0.66...

答案 1 :(得分:2)

  

您需要将总数添加到之前的值。

total = count(); //this replaces the original total.

使用

total = total + count();

total += count();

平均值

total / array.length //array.length would return the total number of elements in it.(here 3)

答案 2 :(得分:0)

如果您使用的是Java 8,则可以按如下方式简化计数逻辑:

String[] array = new String[]{"hie","raisin","critical"};
String target = "i";
double count = Arrays.stream(array).map(s->s.split("")).flatMap(Arrays::stream).filter(ch->ch.equals(target)).count();
double average = count/array.length;
System.out.println(average);