Created
August 17, 2011 11:05
-
-
Save gjoseph/1151330 to your computer and use it in GitHub Desktop.
Why are there so many ways of getting a String[] from a comma-separated String in Java, and none of the basic ones really work (split(",") or StringTokenizer) ? I don't know, but this is my ultimate solution at the moment. Are there more cases to cover ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.regex.Pattern; | |
public class SplitUtil { | |
private static final Pattern COMMA_DELIMITED_SPLIT = Pattern.compile("(\\s*,\\s*)+"); | |
private static final String[] EMPTY = new String[0]; | |
public static String[] commaDelimited(String s) { | |
if (s == null) { | |
return EMPTY; | |
} | |
s = s.trim(); | |
if (s.length() == 0) { | |
return EMPTY; | |
} | |
return COMMA_DELIMITED_SPLIT.split(s, 0); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Test; | |
import static org.junit.Assert.assertArrayEquals; | |
public class SplitUtilTest { | |
@Test | |
public void commaDelimitedBasicTest() { | |
assertArrayEquals(new String[]{"abc", "def"}, SplitUtil.commaDelimited("abc,def")); | |
} | |
@Test | |
public void commaDelimitedRemovesWhiteSpaceAroundCommas() { | |
assertArrayEquals(new String[]{"abc", "def"}, SplitUtil.commaDelimited(" abc , \tdef ")); | |
} | |
@Test | |
public void commaDelimitedCanDealWithSingleElement() { | |
assertArrayEquals(new String[]{"abc"}, SplitUtil.commaDelimited("abc")); | |
assertArrayEquals(new String[]{"abc"}, SplitUtil.commaDelimited(" abc ")); | |
} | |
@Test | |
public void commaDelimitedReturnsEmptyArrayForEmptyInput() { | |
assertArrayEquals(new String[]{}, SplitUtil.commaDelimited("")); | |
} | |
@Test | |
public void commaDelimitedReturnsEmptyArrayForNullInput() { | |
assertArrayEquals(new String[]{}, SplitUtil.commaDelimited(null)); | |
} | |
@Test | |
public void commaDelimitedReturnsEmptyArrayForSpaceOnlyInput() { | |
assertArrayEquals(new String[]{}, SplitUtil.commaDelimited(" ")); | |
} | |
@Test | |
public void commaDelimitedReturnsEmptyArrayForCommaOnlyInput() { | |
assertArrayEquals(new String[]{}, SplitUtil.commaDelimited(",")); | |
assertArrayEquals(new String[]{}, SplitUtil.commaDelimited(" , ")); | |
assertArrayEquals(new String[]{}, SplitUtil.commaDelimited(",,")); | |
assertArrayEquals(new String[]{}, SplitUtil.commaDelimited(" , ,")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment