Vince
Vince

Reputation: 15146

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

Upvotes: 12

Views: 1593

Answers (4)

Christian Tapia
Christian Tapia

Reputation: 34176

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"

Upvotes: 24

Ingo
Ingo

Reputation: 36339

It is here "line\nAnd"

When you print this, it comes out as

line
And

Upvotes: 5

SK.
SK.

Reputation: 4358

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.

if (s.contains("\n")) {
    System.out.print(s);
}

Output:

line
And

Upvotes: 2

ps-aux
ps-aux

Reputation: 12174

There is no line and And. It's line\nAnd. You have seen in console:

line
And

exactly because of the line break character \n.

So its; in the middle and if you change the code to s.contains("\n")). You will see it.

Upvotes: 2

Related Questions