简体   繁体   English

如何基于换行符拆分Java字符串

[英]How to split a java string based on newline character

I have a string in java defined as below: 我在java中定义了一个字符串,如下所示:

String numbers = null;
for (int i= 0; i < contactNumberList.size();i++)
{
    numbers = contactNumberList.get(i) + "\n" + numbers;
}

where contactNumberList contains four items as : 9891, 3432, 5432, 9890. So after the loop i have numbers string as: 9890\\n5432\\n3432\\n9891\\nnull 其中contactNumberList包含四个项目,分别为:9891,3432,5432,9890。因此,在循环之后,我得到的数字字符串为: 9890 \\ n5432 \\ n3432 \\ n9891 \\ nnull

Then i passed the above string through following APIs. 然后,我通过以下API传递了上述字符串。

String toUnicodeEncoded = StringEscapeUtils.escapeJava(numbers);
toUnicodeEncoded = StringEscapeUtils.escapeXml10(toUnicodeEncoded);

Now when i try to print the string toUnicodeEncoded character by character as below: 现在,当我尝试按字符将字符串打印为UnicodeEncoded字符时,如下所示:

for (int i =0;i<toUnicodeEncoded.length();i++)
{
   Logger.log("chat at  "+i + " = "+(toUnicodeEncoded.charAt(i)));
}

It gives : 它给 :

char at 0 = 9
char at 1 = 8
char at 2 = 9
char at 3 = 0
char at 4 = \
char at 5 = n

and so on . 等等 。

My point is "\\n" became two characters \\ and n . 我的观点是“ \\ n”变成了两个字符\\和n。 Now i wanted to split the string toUnicodeEncoded based on "\\n" using the following APIs: 现在,我想使用以下API将字符串基于“ \\ n”拆分为UnicodeEncoded

String lines[] = toUnicodeEncoded.split("\\n");

But its not able to split it because now "\\n" has become \\ and n. 但是它无法拆分它,因为现在“ \\ n”已变成\\和n。 How do i split toUnicodeEncoded string by "\\n" or new line character. 如何通过“ \\ n”或换行符将其拆分为Unicode编码的字符串。

BAsically i want the output as : 我基本上希望输出为:

9890
5432
3432
9891
null

ie all four numbers . 即所有四个数字。 How do i do it. 我该怎么做。

When we split your string with \\n it is giving expected output. 当我们用\\ n分割字符串时,它会提供预期的输出。 But it is better to use System.getProperty("line.separator") instead of \\n 但是最好使用System.getProperty("line.separator")代替\\n

String s="9890\n5432\n3432\n9891\nnull";
s = StringEscapeUtils.escapeJava(s);
s= StringEscapeUtils.escapeXml10(s);

for (String number:s.split("\n")) {
    System.out.println(number);
}

result 结果

9890
5432
3432
9891
null

使用这个,应该做的把戏

String.split("[\\r\\n]+")

Thanks everybody for replying. 谢谢大家的回复。 But i got it working using following approach: 但是我使用以下方法使其工作:

String pattern = Pattern.quote("\\" + "n");
String lines[] = toUnicodeEncoded.split(pattern);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM