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

时间:2019-05-01 20:23:17

标签: 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.

3 个答案:

答案 0 :(得分:1)

遍历您创建的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.

答案 1 :(得分:0)

使用IntStream代替for循环的更优雅的解决方案:

import java.util.stream.IntStream;

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

        String[] splitted = sentence.split("\\s+");
        IntStream.range(0, splitted.length)
                .mapToObj(i -> (i + 1) + " " + splitted[i])
                .forEach(System.out::println);

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

答案 2 :(得分:0)

尝试避免过多的复杂性,下面的方法就可以了

public class MySentenceCounter {
    public static void main(String[] args) {
        String sentence = "This is my sentence and it is not great";
        int ctr = 0;
        for (String str : sentence.trim().split("\\s+")) {
            System.out.println(++ctr + "" + str) ;
         } 
         System.out.println("Total is " + ctr + " words.");
    }
}