java - 有没有办法 println 来枚举和列出字符串中的单词?

标签 java arrays string counting

我正在尝试编写一个java程序,该程序将计算声明句子中的单词数,然后将句子分解为单词,以便列出具有数值的单词并显示单词。我已经解决了总数,但我似乎无法分解句子中的单词,然后按时间顺序列出它们。我可以用字符来完成,但不能用文字来完成。

我已经探索了 Java Cookbook 和其他地方来寻找解决方案,但我只是不太理解它。正如我所说,我可以计算字符数,也可以计算单词数,但无法将各个单词打印在单独的行上,并在字符串中计算它们的计数值。

public class MySentenceCounter {
    public static void main(String[] args) {
        String sentence = "This is my sentence and it is not great";

        String[] wordArray = sentence.trim().split("\\s+");
        int wordCount = wordArray.length;
        for (int i=0; i < sentence.length(  ); i++)
            System.out.println("Char " + i + " is " + sentence.charAt(i)); 
        //this produces the character count but I need it to form words, not individual characters.

        System.out.println("Total is " + wordCount + " words.");
    }
}

预期结果应如下所示:

1 This
2 is
3 my
4 sentence
5 and
6 it
7 is
8 not
9 great
Total is 9 words.

最佳答案

迭代您创建的 wordArray 变量,而不是 for 循环中的原始 sentence 字符串:

public class MySentenceCounter {
  public static void main(String[] args) {
    String sentence = "This is my sentence and it is not great";
    String[] wordArray = sentence.trim().split("\\s+");
    // String[] wordArray = sentence.split(" "); This would work fine for your example sentence
    int wordCount = wordArray.length;
    for (int i = 0; i < wordCount; i++) {
      int wordNumber = i + 1;
      System.out.println(wordNumber + " " + wordArray[i]);
    }
    System.out.println("Total is " + wordCount + " words.");
  }
}

输出:

1 This
2 is
3 my
4 sentence
5 and
6 it
7 is
8 not
9 great
Total is 9 words.

关于java - 有没有办法 println 来枚举和列出字符串中的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55942276/

相关文章:

.net - 使用 array.resize 而不是 redim 的原因

c++ - 哪种字符串查找算法适用于此?

string - 修剪所有类型的空白,包括制表符

java - 测试客户端服务器

java - json(使用google gson)字符串的UTF 8解码问题

java - DefaultTableModel 不返回 dataVector 中的值

java - 无法使用按钮

C 程序在不使用 string.h 库的情况下检索两个字符之间的文本

arrays - 有条件地减少 Mongo 聚合中的两个数组字段

c - 修改用户输入文件路径以扫描C中同一目录中的文件