Avinash Mishra
Avinash Mishra

Reputation: 1516

Why I cannot split string with $ in Java

I was just doodling on eclipse IDE and written following code.

String str = new String("A$B$C$D");
String arrStr[] = str.split("$");
for (int i = 0; i < arrStr.length; i++) {
    System.out.println("Val: "+arrStr[i]);
}

I was expecting output like: Val: A Val: B Val: C Val: D
But instead of this, I got output as

Val: A$B$C$D Why? I am thinking may be its internally treated as a special input or may be its like variable declaration rules.

Upvotes: 6

Views: 5659

Answers (5)

VWeber
VWeber

Reputation: 1261

You have to escape "$":

arrStr = str.split("\\$");

Upvotes: 8

petritz
petritz

Reputation: 182

Its simple. The "$" character is reserved that means you need to escape it.

String str = new String("A$B$C$D");
String arrStr[] = str.split("\\$");
for (int i = 0; i < arrStr.length; i++) {
    System.out.println("Val: "+arrStr[i]);
}

That should work fine. So whenever something like this happens escape the character!

Upvotes: 1

Gerald M&#252;cke
Gerald M&#252;cke

Reputation: 11132

The split() method accepts a string that resembles a regular expression (see Javadoc). In regular expressions, the $ char is reserved (matching "the end of the line", see Javadoc). Therefore you have to escape it as Avinash wrote.

String arrStr[] = str.split("\\$");

The double-backslash is to escape the backslash itself.

Upvotes: 3

Estimate
Estimate

Reputation: 1461

You have used $ as regex for split. That character is already defined in regular expression for "The end of a line" (refer this). So you need to escape the character from actual regular expression and your splitting character should be $.

So use str.split("\\$") instead of str.split("$") in your code

Upvotes: 4

Uli
Uli

Reputation: 1500

The method String.split(String regex) takes a regular expression as parameter so $ means EOL.

If you want to split by the character $ you can use

String arrStr[] = str.split(Pattern.quote("$"));

Upvotes: 11

Related Questions