开发者

How can I split a string into words, spaces and newlines?

开发者 https://www.devze.com 2023-02-24 00:25 出处:网络
I\'m using the Play Framework and taking a text from a textarea and I want to split it into an array of the words, spaces and newlines that was entered.

I'm using the Play Framework and taking a text from a textarea and I want to split it into an array of the words, spaces and newlines that was entered.

Hello World How

Are You

Would开发者_JS百科 be something like

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

If there is a simple regex way or something similar I would love to hear about it?


Try this code:

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"


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


StringTokenizer would work.

0

精彩评论

暂无评论...
验证码 换一张
取 消