2015-10-17 55 views
0

編寫一個名爲wordCount的方法,該方法接受String作爲其參數並返回String中的單詞數。一個單詞是一個或多個非空格字符(除''之外的任何字符)的序列。例如,調用wordCount(「hello」)應該返回1,調用wordCount(「你好嗎?」)應該返回3,調用wordCount(「this string has wide spaces」)應該返回5,調用wordCount (「」)應返回0.寫一個方法來返回字符串中的字數?編輯

好吧,所以我的問題是,當程序輸入的字符串/短語單詞用空格而不是單詞開頭 時,它不會在句子中註冊以下單詞並且返回值1.

所以如果wordCount是(「這個字符串有很寬的空間」) 哪些應該返回5但只是退休0.我不明白爲什麼你能幫我理解我在哪裏搞砸了?

這裏是我的方法:

public static int wordCount(String s) { 
      int word = 0; 
      if(s!=null) 
      if(s.charAt(0)!=' ') { 
       word++; 
      } 
      for(int i=0; i<=s.length(); i++)  
      { 
      if(s.charAt(i)!=' ' && s.charAt(i+1) ==' ')  
      { 
       word++; 
      } 
       return word; 
     } 
      return word; 
    } 
+0

甲'char'不能相比於空'String',作爲誤差表示。你打算檢查角色是否是空間? 's.charAt(0)!'''' – Andreas

+0

http://stackoverflow.com/questions/8102754/java-word-count-program谷歌首先命中:「java字數」 – kongebra

+0

@Andreas \t 是我想它會查看是否存在空格並跳過它,以便只計算單詞並且不在計數中包含空格。每當我將「」更改爲「'我收到更多的錯誤通知...... – TeSa

回答

0
public static int wordCount(String s) { 
    if(s!=null) 
     return s.trim().split(" ").length ; 
    return 0; 
} 
0

我將通過定義完成開始。通常,這就是您的功能定義完成的時間。一個這樣的例子(從你的問題),可能看起來像

public static void main(String[] args) { 
    String[] inputs = { "hello", "how are you?", 
      " this string has wide spaces ", " " }; 
    int[] outputs = { 1, 3, 5, 0 }; 
    String[] inputs = { "hello", "how are you?", 
      " this string has wide spaces ", " " }; 
    int[] outputs = { 1, 3, 5, 0 }; 
    for (int i = 0; i < outputs.length; i++) { 
     System.out.printf("Expected: %d, Actual: %d, %s%n", 
       wordCount(inputs[i]), outputs[i], 
       wordCount(inputs[i]) == outputs[i] ? "Pass" : "Fail"); 
    } 
} 

wordCount方法需要考慮null。接下來,您可以使用String.split(String)來創建令牌數組。所有你感興趣的是它的長度。像

public static int wordCount(String s) { 
    String t = (s == null) ? "" : s.trim(); 
    return t.isEmpty() ? 0 : t.split("\\s+").length; 
} 

它通過您提供的測試條件下,生成所述輸出

Expected: 1, Actual: 1, Pass 
Expected: 3, Actual: 3, Pass 
Expected: 5, Actual: 5, Pass 
Expected: 1, Actual: 1, Pass 
相關問題