public static String [ ] splitShortString ( String str , char separator ) { int len = ( str == null ) ? 0 : str . length ( ) ; if ( str == null || len == 0 ) { return org . apache . myfaces . shared . util . ArrayUtils . EMPTY_STRING_ARRAY ; } int lastTokenIndex = 0 ; // Step 1: how many substrings? // We exchange double scan time for less memory allocation for ( int pos = str . indexOf ( separator ) ; pos >= 0 ; pos = str . indexOf ( separator , pos + 1 ) ) { lastTokenIndex ++ ; } // Step 2: allocate exact size array String [ ] list = new String [ lastTokenIndex + 1 ] ; int oldPos = 0 ; // Step 3: retrieve substrings int pos = str . indexOf ( separator ) ; int i = 0 ; while ( pos >= 0 ) { list [ i ++ ] = substring ( str , oldPos , pos ) ; oldPos = ( pos + 1 ) ; pos = str . indexOf ( separator , oldPos ) ; } list [ lastTokenIndex ] = substring ( str , oldPos , len ) ; return list ; }
Split a string into an array of strings arround a character separator . This function will be efficient for short strings for longer strings another approach may be better