Strange String.split(“\n”) behavior

2020-01-31 08:23发布

I have a .txt text file, containing some lines.. I load the contain using the RequestBuilder object, and split the responseText with words = String.split("\n"); but i wonder, why the result is contains the "\n" part.. For example, my text:

abc
def
ghi

the result is,

words[0] = "abc\n"
words[1] = "def\n"
words[2] = "ghi\n"

Any help is highly appreciated. Thanks in advance.

标签: java split
5条回答
SAY GOODBYE
2楼-- · 2020-01-31 08:52

Try using string.split("\\n+"). Or even better - split("[\\r\\n]+")

查看更多
劫难
3楼-- · 2020-01-31 08:57

Windows carriage returns ("\r\n") shouldn't make a visible difference to your results, nor should you need to escape the regular expression you pass to String.split().

Here's proof of both the above using str.split("\n"): http://ideone.com/4PnZi

If you do have Windows carriage returns though, you should (although strictly not necessary) use str.split("\r\n"): http://ideone.com/XcF3C

查看更多
霸刀☆藐视天下
4楼-- · 2020-01-31 08:58

If split uses regex you should use "\\n" instead of "\n"

查看更多
我想做一个坏孩纸
5楼-- · 2020-01-31 09:00

You may also want to consider String[] lines = text.split("\\\\n");

查看更多
beautiful°
6楼-- · 2020-01-31 09:06

Try using string.split("\\\\n") . It works for me.

查看更多
登录 后发表回答