public static String [ ] split ( final CharSequence charSequence , final char separator ) { if ( isEmpty ( charSequence ) ) { return EMPTY_ARRAY ; } final int originalSeparatorsCount = countSeparatedCharAppearances ( charSequence , separator ) ; int separatorsCount = originalSeparatorsCount ; // If the sequence starts or ends with the separator (and its not the same char index), we don't need as many // characters. if ( startsWith ( charSequence , separator ) ) { separatorsCount -- ; } if ( charSequence . length ( ) > 1 && endsWith ( charSequence , separator ) ) { // Length has to be at least 2, as we want to check two different chars and subtract count only once. separatorsCount -- ; } if ( separatorsCount <= 0 ) { if ( originalSeparatorsCount == 0 ) { // No separators at all. return new String [ ] { charSequence . toString ( ) } ; } else if ( isSameChar ( charSequence ) ) { // We've confirmed that the sequence contains a separator and consists of only 1 type of character. It // means that the whole string is made of separators, so we're returning empty array. return EMPTY_ARRAY ; } // No separators inside the sequence, but found on edges. Returning the whole string, possibly with stripped // separators. return new String [ ] { removeCharacter ( charSequence . toString ( ) , separator ) } ; } final String [ ] result = new String [ separatorsCount + 1 ] ; int currentResultIndex = 0 ; final StringBuilder builder = new StringBuilder ( ) ; for ( int index = 0 , length = charSequence . length ( ) ; index < length ; index ++ ) { final char character = charSequence . charAt ( index ) ; if ( character == separator ) { if ( isNotEmpty ( builder ) ) { result [ currentResultIndex ++ ] = builder . toString ( ) ; clearBuilder ( builder ) ; } } else { builder . append ( character ) ; } } if ( isNotEmpty ( builder ) ) { // The whole thing may not end with a separator, so we're appending whatever we got left. result [ currentResultIndex ++ ] = builder . toString ( ) ; } return result ; }
As opposed to string s split this method allows to split a char sequence without a regex provided that the separator is a single character . Since it does not require pattern compiling and is a simple iteration this method should be always preferred when it can be used .