2013-12-09 60 views
2

基本上我需要做的僅僅是一個句子的前十個單詞存入數組的數組。我從我的代碼,如果是大於10,所有的字將被保存知道,但我只能通過循環10次,停止迭代。但是,如果句子少於10個單詞,我需要用空字符串填充它。所以如果它有10個或更多的單詞,我可以讓它工作。但是,如果少於10個單詞,我無法使其工作。有誰知道一種方法使其工作?我必須有10字符串分割爲已定義

String[] tempString = new String[10]; 
    tempString = sentence.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+"); 
    for(int i = 0; i < tempString.length; i++) 
    { 
     System.out.println(tempString[i]); 
    } 

編輯數組大小:

所以基本上,如果我進入了一句:「一二三四五六七八九十」,它會工作。但是,如果我輸入「一,二,三」那就給我一個ArrayOutofBoundsException。我需要填充的其他7個索引是空字符串。

回答

2

您可以使用以下方法:

for(int i = 0; i < 10; i++) 
    { 
     if (i < tempString.length) 
      System.out.println(tempString[i]); 
     else 
      System.out.println(""); 
    } 

由於需要10張,那麼你重複10次。每次迭代檢查你是否仍然在分割的字符串數組中。如果不是隻按照你的願望填充剩餘空間。

+0

這對我來說更高效的選擇。謝謝! – tjg92

0

有2種方法來實現這個..

  1. Initailize所有字符串爲空「」(在for循環..)調用在你的代碼所示循環之前。

  2. 循環,如果長度小於10之後,然後將剩餘的項目爲 「」

    如果(tempString.length < 10);

    int diff = 10 - tempString.length -1;

環DIFF倍,並添加 「」 每次..

很抱歉的格式..

0
String[] tempString = Arrays.copyOf(sentence.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+"), 10); 
1

做這樣

if(tempString.length<10) 
    tempString = Arrays.copyOf(tempString, 10); 
1
String[] tempString = new String[10]; 
tempString = sentence.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+"); 

上面兩行沒有太大意義。第一行創建一個長度爲10的新數組,並將其分配給變量tempString,但第二行說:讓我們忘掉這個數組,並將一個包含句子所有單詞的新數組重新分配到tempString變量。

所以你實際上需要兩個變量:

String[] result = = new String[10]; 
String allWords = sentence.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+"); 

// now copy at most 10 elements from allWords to result: 
for (int i = 0; i < result.length && i < allWords.length; i++) { 
    result[i] = allWords[i]; 
} 

// and now initialize the rest of the array with empty strings 
for (int i = allWords.length; i < result.length; i++) { 
    result[i] = ""; 
}