簡體   English   中英

查找句子中單詞數的簡單Java程序

[英]Simple java program that finds the number of words in a sentence

  public static String number(String words) {
      int length = words.length;
      int total = 0;
      while(int index < length) {
          total = total + 1;
          index = index + 1;
          }
      }
      String output;
      output = total + " word";
      return output;
  }

輸出示例如下:

numberOfWords("Hello whats up?")
3 word

這適用於所有適當的句子,但我必須考慮輸入錯誤的情況,例如:

"Hi             my         name      is bob"

,這將是三十多個單詞。

"                 "

,應為0個字。 有沒有簡單的方法可以使第一個示例成為“嗨,我叫鮑勃”?

您可以執行以下操作

String trimmed = text.trim();
int words = trimmed.isEmpty() ? 0 : trimmed.split("\\s+").length;

或(最簡單的方法):

use str.replaceAll("\\s+"," "); 

最簡單的方法在每種情況下都適用

        String word = "Hi             my         name      is bob";
        word = word.replaceAll("\\s+", " ");
        String count [] = word.split(" ");

        System.out.println(count.length);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM