Example 1:
public class StringSplit {
public static void main(String args[]) throws Exception{
new StringSplit().doit();
}
public void doit() {
String s3 = “Real-How-To”;
String [] temp = null;
temp = s3.split(“-”);
dump(temp);
}
public void dump(String []s) {
System.out.println(“————”);
for (int i = 0 ; i < s.length ; i++) {
System.out.println(s[i]);
}
System.out.println(“————”);
}
}
/*
output :
————
Real
How
To
————
*/
split() is based on regex expression, a special attention is needed with some characters which have a special meaning in a regex expression.
For example :
String s3 = “Real.How.To”;
…
temp = s3.split(“\\.”);
or
String s3 = “Real|How|To”;
…
temp = s3.split(“\\|”);
The special character needs to be escaped with a “\” but since “\” is also a special character in Java, you need to escape it again with another “\” !



An interesting thing about String.split():
” s”.split(” “) -> {“”,”",”s”}
“”.split(“” ) -> {“”}
” “.split(” “) -> {} (!)
” “.split(” “) -> {} (!)
” s “.split(” “) -> {“”,”",”s”} (!)