Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is \n located in a String?

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)?

like image 691
Vince Avatar asked Jan 19 '14 21:01

Vince


1 Answers

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"

like image 118
Christian Tapia Avatar answered Sep 22 '22 21:09

Christian Tapia