为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

长风秋雁 2022-11-02 15:58:36
我正在尝试编写一个 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 This2 is3 my4 sentence5 and6 it7 is8 not9 greatTotal is 9 words.
查看完整描述

3 回答

?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

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


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.


查看完整回答
反对 回复 2022-11-02
?
饮歌长啸

TA贡献1951条经验 获得超3个赞

尽量避免过于复杂,下面的就行了


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.");

    }

}


查看完整回答
反对 回复 2022-11-02
?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

使用 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.");

    }

}


查看完整回答
反对 回复 2022-11-02
  • 3 回答
  • 0 关注
  • 118 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信