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.
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("$"));
You have to escape "$":
arrStr = str.split("\\$");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With