I have a have a String which came from a text area: (with the variable name 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"
for(String s : string.split(" ")) {
if(s.contains("\n"))
System.out.println(s);
}
Both line
and And
in my sentence contain \n
. But, if I were to check if the word either started with \n
or ended with it, it gives me no results.
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)
?
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 (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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With