2011-04-13 87 views
2

我正在使用Play框架並從textarea中獲取文本,我想將其分割爲輸入的單詞,空格和換行符的數組。如何將字符串拆分爲單詞,空格和換行符?

的Hello World

你好嗎

會像

a[0] = "Hello"; 
a[1] = " "; 
a[2] = "World"; 
a[3] = " "; 
a[4] = "How"; 
a[5] = "\n"; 
a[6] = "Are"; 
a[7] = " "; 
a[8] = "You"; 

如果有一個簡單的正則表達式的方式或類似的東西我也喜歡聽到了嗎?

+2

這似乎是http://stackoverflow.com/questions/275768/is-there-a-way-to-split-strings-with-string-split-and-include-the-的副本分隔符 – worpet 2011-04-13 01:55:49

+0

這可能是解決方案。去看看它。 – 2011-04-13 01:59:11

回答

3
st = new java.util.StringTokenizer (text, "[ \t\n]", true) 
+1

@ÓlafurWaage:* StringTokenizer是一個遺留類,由於兼容性的原因而被保留,儘管它在新代碼中的使用**不鼓勵**。建議任何需要此功能的人都使用String或java.util.regex包的拆分方法。*從Javadocs:http://download.oracle.com/javase/6/docs/api/java/util/ StringTokenizer.html – anubhava 2011-04-13 11:56:15

6

試試這個代碼:

String str = "Hello World How\nAre You"; 
String[] inputs = str.split("(?!^)\\b"); 
for (int i=0; i<inputs.length; i++) { 
    System.out.println("a[" + i + "] = \"" + inputs[i] + '"'); 
} 

OUTPUT: 
a[0] = "Hello" 
a[1] = " " 
a[2] = "World" 
a[3] = " " 
a[4] = "How" 
a[5] = " 
" 
a[6] = "Are" 
a[7] = " " 
a[8] = "You" 
相關問題