Wednesday, April 21, 2010

Java Split String

Java has a useful method to slip the string into a string array based on the delimiter. Its the Split() method.

But most of the time we may use it incorrectly. One example is, if we have a string with comma separated values, Split can be used to split the comma separated values into String[]. But if we use this directly, most of us might have noticed that it does not consider the last trailing string.

ie., if the string is String str = "a,b,c,d,";
When we do String[] strArray = str.split(","); we get the string array with 4 values only. And not with 5 values. To get the complete string array, we must use as below;
String[] strArray = str.split(",", -1);

This is generally useful when you have multiple rows of such comma separated string or the string is dynamically created.