java - 使用JAVA统计一个单词出现了多少次

标签 java count stringtokenizer

标记然后计算该单词出现的次数

示例:“敏捷的棕色狐狸”

预期输出:

- 1 快 - 2 棕色 - 1 狐狸 - 1

public class Tokenizer
{
  public static void main(String[] args)
  {
    int index = 0; int tokenCount;
    String words[] = new String [50];
    String message="The Quick brown fox the";

    StringTokenizer string = new StringTokenizer(message);

    tokenCount = string.countTokens();
    System.out.println("Number of tokens = " + tokenCount);
    while (string.hasMoreTokens()) 
        { words[index] = string.nextToken(); index++; }
    for (index=0;index<tokenCount; index++)
        { System.out.println(words[index]); }
  }
}

最佳答案

这里需要使用一个java.util.Map来维护单词和对应的计数:

import java.util.Map;
import java.util.HashMap;
public class Tokenizer
{
  public static void main(String[] args)
  {
    int index = 0; int tokenCount;
    Map<String,Integer> wordCount = new HashMap<String,Integer>();
    String message="The Quick brown fox the";

    StringTokenizer string = new StringTokenizer(message);

    tokenCount = string.countTokens();
    System.out.println("Number of tokens = " + tokenCount);
    while (string.hasMoreTokens()) { 
          String word = string.nextToken();
          Integer count = wordCount.get(word);
          if(count == null) { //this means the word was encountered the first time
          wordCount.put(word, 1);
        }
        else { //word was already encountered we need to increment the count
          wordCount.put(word, count + 1);
        }
     }
    for (String words : wordCount.keySet())
        { System.out.println("Word : " +  word + " has count :" +wordCount.get(word); 
    }
  }
}

关于java - 使用JAVA统计一个单词出现了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33729390/

相关文章:

PHP 和 MySQL 投票系统 OOP

java - StringTokenizer 使用

Java如何拆分arralyist并设置为单独的字符串或数组

java - 在触摸坐标上创建 View ,但给出了错误的 x 和 y

java - 成功后,步骤无法在 travis-ci 构建中的项目根目录下找到文件

Java:从 Linux 机器访问 Windows 文件

c - 使用 strchr() 计算字符串中字符的出现次数

java - Spring Batch - 在 Eclipse 中作为应用程序运行 - SQLException 无效的模式名称 - JUnit

sql - 如何在同一 select 语句中使用 count 和 group by

java - 检查字符串中的大写字母并找到位置