java - 想要统计Java中字符串的出现次数

标签 java string count

所以我有一个 .txt 文件,我正在使用它调用

String[] data = loadStrings("data/data.txt");

文件已经排序,基本上看起来像:

Animal
Animal
Cat
Cat
Cat
Dog

我正在寻找一种算法来计算java中的排序列表,而不使用任何像Multisets这样的库或不使用Maps/HashMaps。到目前为止,我已经设法让它打印出出现次数最多的单词,如下所示:

ArrayList<String> words = new ArrayList();

int[] occurrence = new int[2000];
Arrays.sort(data);

for (int i = 0; i < data.length; i ++ ) {
words.add(data[i]);     //Put each word into the words ArrayList
}
for(int i =0; i<data.length; i++) {
 occurrence[i] =0;
 for(int j=i+1; j<data.length; j++) {
   if(data[i].equals(data[j])) {
     occurrence[i] = occurrence[i]+1;
   }
 }
}
int max = 0;
String most_talked ="";
for(int i =0;i<data.length;i++) {
  if(occurrence[i]>max) {
    max = occurrence[i];
    most_talked = data[i];
  }
 }
 println("The most talked keyword is " + most_talked + " occuring " + max + " times.");

我想要的不仅仅是获得出现次数最多的单词(可能是前 5 名或前 10 名)。 希望这已经足够清楚了。感谢您的阅读

最佳答案

既然你说你不想使用某种数据结构,我认为你可以做这样的事情,但它的性能不高。 我通常更喜欢存储索引而不是值。

ArrayList<String> words = new ArrayList();

int[] occurrence = new int[2000];
Arrays.sort(data);


int nwords = 0;
occurrence[nwords]=1;
words.add(data[0]);        
for (int i = 1; i < data.length; i ++ ) {
    if(!data[i].equals(data[i-1])){ //if a new word is found
        words.add(data[i]);         //put it into the words ArrayList
        nwords++;                   //increment the index
        occurrence[nwords]=0;       //initialize its occurrence counter
    }
    occurrence[nwords]++;           //increment the occurrence counter
}

int max;
for(int k=0; k<5; k++){  //loop to find 5 times the most talked word
  max = 0;               //index of the most talked word
  for(int i = 1; i<words.size(); i++) { //for every word
    if(occurrence[i]>occurrence[max]) { //if it is more talked than max
      max = i;                          //than it is the new most talked
    }
  }
  println("The most talked keyword is " + words.get(max) + " occuring " + occurence[max] + " times.");
  occurence[max]=0;
}

每次我找到具有较高出现值的值时,我都会将其出现计数器设置为 0,然后再次重复该数组,重复 5 次。

关于java - 想要统计Java中字符串的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29323751/

相关文章:

java - 使用没有语句的 apache dbutils 获取自动增量生成的 key

字符串 CONSTRAINT_ERROR 长度检查失败

php - 显示类(class)注册学生总数

c++ - 删除从 i 到行尾的字符串的一部分

C++:仅使用 STL 从字符串中提取标记

r - 计算未出现较早且未出现在最后一组中的新值

java - Spring Boot自定义查询分组依据和计数

java - 从预定义数据构建 HttpServletRequest

java - 警告 : while trying to convert java byte[] to C unsigned char*

java - 为什么它给我一个 "method call expected"错误?