Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior of split String method [duplicate]

Tags:

java

string

split

Consider these simple lines of code:

public class Main {

    public static void main(String[] args) {

        String string = "Lorem,ipsum,dolor,sit,amet";
        String[] strings = string.split(",");

        for (String s : strings) {
            System.out.println(s);
        }
    }
}

As expected, the output is the following:

Lorem
ipsum
dolor
sit
amet

Now consider a variation of the previous code, in which I simply turned , into |:

public class Main {

    public static void main(String[] args) {

        String string = "Lorem|ipsum|dolor|sit|amet";
        String[] strings = string.split("|");

        for (String s : strings) {
            System.out.println(s);
        }
    }
}

I expect the same exact output, but it is strangely the following:

L
o
r
e
m
|
i
p
s
u
m
|
d
o
l
o
r
|
s
i
t
|
a
m
e
t

What's wrong?

like image 802
ᴜsᴇʀ Avatar asked Mar 15 '23 20:03

ᴜsᴇʀ


1 Answers

String#split() method accepts a regex and | have a special meaning in regex.

To see expected result escape that |.

String[] splits=string.split("\\|");

Or you can use Pattern class, to avoid all the mess.

String[] splits= string.split(Pattern.quote("|"));
like image 185
Suresh Atta Avatar answered Mar 23 '23 09:03

Suresh Atta