Q:

Java String Split Behavior - Split on Dollar Symbol

I am trying the following code (running java version 1.7 in Eclipse Luna IDE on Ubuntu Linux 12.04):
String str = "abc$xyz"; 
String[] split_ = str.split("$");
System.out.println(split_.length);

I am always getting a split of length 1. If I try to print split_[0], I am always getting the entire string. Can anyone suggest what might be the cause?

A:

This is because split expects a regular expression. Since "$" is the end-of-line marker in a regular expression, this only splits on the end of the String.
You should use
String str = "abc$xyz"; 
String[] split_ = str.split("\\$");
System.out.println(split_.length);

instead.
This escapes the "$", so that it's treated as a literal character instead (and uses two slashes to escape the backslash as part of the string literal).

