如何将字符串拆分为单词,空格和换行符?

时间:2011-04-13 01:49:05

标签: java string split

我正在使用Play Framework并从textarea中获取文本,我想将其拆分为输入的单词,空格和换行符的数组。

  

Hello World How

     

你是

吗?

会像

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

如果有一种简单的正则表达式或类似的东西,我很乐意听到它吗?

3 个答案:

答案 0 :(得分: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"

答案 1 :(得分:3)

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

答案 2 :(得分:0)

StringTokenizer可行。