Tuesday, July 06, 2010

String.split() trivia

The String.split() method converts a given string to an array based on a regular expression.

Examples:


System.out.println( Arrays.toString( "0:1::::".split( "[:]" ) ) );     // Output: [0, 1]

System.out.println( Arrays.toString( "::::4:5".split( "[:]" ) ) );     // Output: [, , , , 4, 5]

System.out.println( Arrays.toString( "0:1::::".split( "[:]", -1 ) ) ); // Output: [0, 1, , , , ]


As the documentation notes, “blah”.split(“:”) is the same as “blah”.split(“:”, 0) which does not include trailing empty strings.

No comments: