[英]Where is \n located in a String?
I have a have a String which came from a text area: (with the variable name string
) 我有一个来自文本区域的String :(带有变量名
string
)
This is the first line
And this is the second
If I were to split that into separate words using string.split(" ")
, then check what words contain "\\n" 如果我使用
string.split(" ")
将它分成单独的单词,那么检查哪些单词包含“\\ n”
for(String s : string.split(" ")) {
if(s.contains("\n"))
System.out.println(s);
}
Both line
and And
in my sentence contain \\n
. 我的句子中的
line
和And
都包含\\n
。 But, if I were to check if the word either started with \\n
or ended with it, it gives me no results. 但是,如果我要检查这个词是以
\\n
开头还是以它结尾,它就没有给我任何结果。
if(s.contains("\n")) {
System.out.println("Contains");
if(s.startsWith("\n"))
System.out.println("Starts with");
else if(s.endsWith("\n")) {
System.out.println("Ends with");
else
System.out.println("Does not contain");
}
My result from that: 我的结果是:
Contains
Does not contain
So, if the word contains a \\n
, but it doesn't start or end with it, where exactly is it and how can I manage it without using replaceAll(String, String)
? 因此,如果单词包含
\\n
,但它不以它开头或结尾,那么它replaceAll(String, String)
以及如何在不使用replaceAll(String, String)
情况下管理它?
What happens is that the string looks like: 会发生什么是字符串看起来像:
"This is the first line\nAnd this is the second"
So when you split it by " "
you get: 因此当你用
" "
分割时,你会得到:
"line\nAnd"
When you print it, it looks like two separate strings.To demonstrate this, try adding an extra print in the for
loop: 当你打印它时,它看起来像两个单独的字符串。
for
证明这一点,尝试在for
循环中添加额外的打印:
for (final String s : string.split(" ")) {
if (s.contains("\n")) {
System.out.print(s);
System.out.println(" END");
}
}
Output: 输出:
line
And END
And when you try to check whether a string starts or ends with "\\n"
you won't get any result because in fact the string "line\\nAnd"
doesn't start or end with "\\n"
当您尝试检查字符串是以
"\\n"
开头还是以"\\n"
结束时,您将无法获得任何结果,因为事实上字符串"line\\nAnd"
不会以"\\n"
开头或结尾
It is here "line\\nAnd"
它在这里
"line\\nAnd"
When you print this, it comes out as 当你打印它时,它出来了
line
And
There is no line and And . 没有线和And 。 It's line\\nAnd .
这是行\\ n和 。 You have seen in console:
你在控制台看到过:
line 线
And 和
exactly because of the line break character \\n . 正是因为换行符\\ n 。
So its; 所以是; in the middle and if you change the code to
s.contains("\\n"))
. 在中间,如果您将代码更改为
s.contains("\\n"))
。 You will see it. 你会看到它。
String : 字符串:
This is the first line\nAnd this is the second
After splitting with " " (space)
you will get output as : line\\nAnd
, so it means string does not start with or end with \\n
. 用
" " (space)
分割后,您将得到输出: line\\nAnd
,因此它表示字符串不以\\n
开头或结尾。
if (s.contains("\n")) {
System.out.print(s);
}
Output: 输出:
line
And
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.