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

我正在尝试编写一个 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.


长风秋雁
浏览 119回答 3
3回答

繁星点点滴滴

迭代wordArray您创建的变量,而不是sentencefor 循环中的原始字符串:public class MySentenceCounter {&nbsp; public static void main(String[] args) {&nbsp; &nbsp; String sentence = "This is my sentence and it is not great";&nbsp; &nbsp; String[] wordArray = sentence.trim().split("\\s+");&nbsp; &nbsp; // String[] wordArray = sentence.split(" "); This would work fine for your example sentence&nbsp; &nbsp; int wordCount = wordArray.length;&nbsp; &nbsp; for (int i = 0; i < wordCount; i++) {&nbsp; &nbsp; &nbsp; int wordNumber = i + 1;&nbsp; &nbsp; &nbsp; System.out.println(wordNumber + " " + wordArray[i]);&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println("Total is " + wordCount + " words.");&nbsp; }}输出:1 This2 is3 my4 sentence5 and6 it7 is8 not9 greatTotal is 9 words.

饮歌长啸

尽量避免过于复杂,下面的就行了public class MySentenceCounter {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; String sentence = "This is my sentence and it is not great";&nbsp; &nbsp; &nbsp; &nbsp; int ctr = 0;&nbsp; &nbsp; &nbsp; &nbsp; for (String str : sentence.trim().split("\\s+")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(++ctr + "" + str) ;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println("Total is " + ctr + " words.");&nbsp; &nbsp; }}

qq_花开花谢_0

使用 IntStream 而不是 for 循环的更优雅的解决方案:import java.util.stream.IntStream;public class ExampleSolution{&nbsp; &nbsp; public static void main(String[] args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; String sentence = "This is my sentence and it is not great";&nbsp; &nbsp; &nbsp; &nbsp; String[] splitted = sentence.split("\\s+");&nbsp; &nbsp; &nbsp; &nbsp; IntStream.range(0, splitted.length)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .mapToObj(i -> (i + 1) + " " + splitted[i])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .forEach(System.out::println);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Total is " + splitted.length + " words.");&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java