2014-02-27 62 views
0

我試圖將String作爲輸入,將其拆分爲空格字符以將單詞存儲在數組中,然後使用這些單詞與其他單詞進行比較。問題是我想在分裂期間被忽略,因爲他們被比較的詞將永遠不會包含句點。按空格拆分字符串並忽略句號

例如:

String testString = "This. is. a. test. string."; 
String[] test = testString.split(" "); 

for (int i = 0; i < test.length; i++) { 
    System.out.println(test[i]); 
} 

這將打印出:

This. 
is. 
a. 
test. 
string. 

相反,我想它打印出來:

This 
is 
a 
test 
string 

我怎能無視期間分裂?

+0

輸入是否總是帶有類似的時期? – csmckelvey

+0

[Java:從字符串中刪除char的所有出現]的可能的重複(http://stackoverflow.com/questions/4576352/java-remove-all-occurances-of-char-from-string) –

回答

5

如何

String[] test = testString.split("\\.[ ]*"); 

String[] test = testString.split("\\.\\s*"); 

或超過一個週期(和省略號)

String[] test = testString.split("\\.+\\s*"); 
+0

在http上更新和測試://regexpal.com/ –

+0

使用\ s *檢查多個空格 –

+0

雖然在示例輸入中這不再是錯誤的,但它僅僅是一個示例。 OP問:「我想在分裂期間忽略一段時間。」我不明白這是如何符合這一要求的。例如,一個帶省略號的句子怎麼樣... – mbroshi

0

更換分裂串replace(".","");

012內的點
+0

爲什麼不把它們刪除?這有什麼不同嗎? –

+1

這個地方的「。」在String數組中。 –

0
public class Main { 
    public static void main(String[] args) { 
     String st = "This. is. a. test. string.""; 
     String[] tokens = st.split(".(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); 
     for(String t : tokens) { 
      System.out.println("> "+t); 
     } 
    } 
} 
1
String[] test = testString.split("\\.\\s*"); 
相關問題