2015-09-26 43 views
0
public static int countWords(String str) 

此方法將計算單詞的數量STR 例如,如果str = "Hi there",該方法將返回2.計數的單詞數在字符串中的日食

我一個初學者,不應該使用預建程序。我知道它可能使用循環,我需要使用.indexOf找到空格?像我的失敗嘗試在底部

public static int countWords(String str){ 
    int count=0; 
    int len=str.length(); 
    if(str.indexOf(" ")>=0){ 
    for(int i=0; i<len; i++) 
     count=count+i; 
    } 
    return count; 
+0

你所說的 「預建計劃」 是什麼意思?你可以使用Scanner類,還是僅限於String類的方法? – Pshemo

+0

@Pshemo我的意思是類似於下面的一些答案:.trim,.split,parts,.isEmpty()。我們還沒有了解NULL,所以我不知道這意味着什麼。 – Maria

回答

0

你可以只寫

public static int countWords(String str){ 
    if(str == null){ 
    return 0; // or your wish to return something 
    } 
    str = str.trim(); 
    return str.split("\\s+").length; 
} 

\\s+將分割字符串甚至還有周圍的空間。

0

當前的實現是完全錯誤的:

  • 如果字符串不包含空格,它不會進入if塊,並錯誤地返回0,因爲這是的count初始值,這是從來沒有改變過
  • 如果字符串包含空格,循環就不是你想要的:它總結了從0到len,例如,如果len = 5,其結果將是0 + 1 + 2 + 3 + 4
  • 沒有什麼在代碼中帳戶爲單詞。請注意,計算空間是不夠的,例如考慮輸入:「你好:-)」。注意單詞之間以及開始和結束之間的過多空格以及非單詞笑臉。

這應該是相對強勁:

int countWords(String text) { 
    String[] parts = text.trim().split("\\W+"); 
    if (parts.length == 1 && parts[0].isEmpty()) { 
     return 0; 
    } 
    return parts.length; 
} 

繁瑣的if條件有處理一些特殊的情況:

  • 空字符串
  • 串唯一的非單詞字符

單元測試:

@Test 
public void simple() { 
    assertEquals(4, countWords("this is a test")); 
} 

@Test 
public void empty() { 
    assertEquals(0, countWords("")); 
} 

@Test 
public void only_non_words() { 
    assertEquals(0, countWords("@#$#%")); 
} 

@Test 
public void with_extra_spaces() { 
    assertEquals(4, countWords(" this is a test ")); 
} 

@Test 
public void with_non_words() { 
    assertEquals(4, countWords(" this is a test :-) ")); 
} 
0
import java.util.Scanner; 

public class CountWordsInString { 
    public static int countWords(String string) { 
     String[] strArray = string.split(" "); 
     int count = 0; 
     for (String s : strArray) { 
      if (!s.equals("")) { 
       count++; 
      } 
     } 
     return count; 
    } 

    public static void main(String args[]) { 
     System.out.println("Enter your string: "); 
     Scanner sc = new Scanner(System.in); 
     String str = sc.nextLine(); 
     System.out.println("Total Words: " + countWords(str)); 
    } 
} 
+1

儘管此代碼可能會回答問題,但提供有關如何解決問題和/或爲何解決問題的其他上下文可以提高答案的長期價值。請閱讀此[如何回答](http://stackoverflow.com/help/how-to-answer)以提供高質量的答案。 – thewaywewere