奇怪的String.split(“\ n”)行为 [英] Strange String.split("\n") behavior
问题描述
我有一个.txt文本文件,包含一些行..
我使用RequestBuilder对象加载包含,并使用
words = String.split(\ n)拆分responseText ;但我想知道,为什么结果包含\ n部分..
例如,我的文字:
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
结果是,
words[0] = "abc\n"
words[1] = "def\n"
words[2] = "ghi\n"
任何帮助都非常感谢。在此先感谢。
Any help is highly appreciated. Thanks in advance.
推荐答案
Windows回车(\\\\ n
)不应该对结果产生明显的影响,也不需要转义传递给 String.split()
的正则表达式。
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()
.
以下是使用 str.split(\ n)
的上述证据: http://ideone.com/4PnZi
Here's proof of both the above using str.split("\n")
: http://ideone.com/4PnZi
如果你做虽然有Windows回车,你应该(尽管严格来说没有必要)使用 str.split(\\\\ n)
: http://ideone.com/XcF3C
If you do have Windows carriage returns though, you should (although strictly not necessary) use str.split("\r\n")
: http://ideone.com/XcF3C
这篇关于奇怪的String.split(“\ n”)行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!