Decrypter
Decrypter

Reputation: 3000

Search a string for newlines within a string just containing "\n"

I have a really annoying issue that I can't fix :(

private static final String NEW_LINE = System.getProperty("line.separator");
text = "\n";
int count = text.split(NEW_LINE).length;

count keeps returning 0 when it should return 1 I think its because \n isnt actually a string but a newline.

Is there a way to fix this?

Upvotes: 2

Views: 537

Answers (4)

gnash117
gnash117

Reputation: 1055

As Peter J said split throws away trailing empty strings.

You could use another method public String[] split(String regex, int limit) with the limit set to -1. This will cause the pattern to be applied as many times as needed and the resulting array can be any length it will not throw away trailing empty strings.

Running the code that you posted always returns 1 for me. That is because it always returns the string[] = {"\n"}

I changed your NEW_LINE to "\\n" and it will return length 2. string[] = {"",""} You will get the empty string before the '\n' and the empty string after the '\n'.

public class splitTest {
    public static void main(String[] args) {
        String text = "\n";
    int count = text.split("\\n", -1).length;
    System.out.println("count = " + count);
    }
}

Upvotes: 0

Peter Jamieson
Peter Jamieson

Reputation: 745

count would only be 1 if /n was not the separator. In the following: -

private static final String COLON = ":";

public static void main(String[] args)
{
    String text = ":";
    int count = text.split(COLON).length;
    System.out.println("len = " + count);
}

count would be zero as well.

split throws away trailing empty strings.
E.g. [x][][] becomes [x], but [x][][][y] stays as it is.

Upvotes: 0

soulcheck
soulcheck

Reputation: 36777

That's because String.split() discards any trailing empty strings in resulting array.

Upvotes: 0

korifey
korifey

Reputation: 3519

Split uses regular expression. Use "\\n" string to split.

Upvotes: 2

Related Questions