Search code examples
javastringapachesplitapache-stringutils

Apache StringUtils Split Function does Crazy


I was wondering about this crazy thing in StringUtils.split(string,separator);

I want to separate a string using a separator @@--@@ and my code goes like this.

String[] strings = StringUtils.split("kayf86@--@9@--@5r43987@!@!%%^&^$%@!@!%-@@*&%$*(&^$%@!@!%--@", "@--@");
for (String string : strings) {
    System.out.println(string);
}

I found the output as such

kayf86
9
5r43987
!
!%%^&^$%
!
!%
*&%$*(&^$%
!
!%

I use commons-lang-2.6.jar Can some one explain that how this thing had happen.


Solution

  • StringUtils uses any of the characters in the separatorChars argument as the separator, not necessarily the whole thing. The javadoc also states

    The separator is not included in the returned String array. Adjacent separators are treated as one separator.

    Parameters

    • separatorChars the characters used as the delimiters, null splits on whitespace

    Alternatively, you can use StringUtils.splitByWholeSeparator(String, String) to split on the exact @--@ or whatever it is.