奇怪的String.split(“\ n”)行为 [英] Strange String.split("\n") behavior

查看:337
本文介绍了奇怪的String.split(“\ n”)行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆