亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有辦法 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 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號