How can a StringBuilder best be converted to a String[]?
Solution 1
So you're just trying to split on tab? How about:
return names.toString().split(TAB);
Note that split
takes a regular expression pattern - so don't expect split(".")
to split just on dots, for example :)
Solution 2
To dynamically grow array, use ArrayList<String>
, you can even convert the result to String[]
if that's what your API requires.
ArrayList<String> namesList = new ArrayList<String>( );
while (-1 != end) {
end = names.indexOf(TAB, start);
namesList.add( names.substring(start, end) );
start = ++end; // The next name is after the TAB
}
return namesList.toArray( new String[ namesList.size( ) ] );
That said, for your purposes use split
as suggested by others
Solution 3
You can use String's method split
to do that in one line.
Solution 4
You can use a recursive implementation to use the program stack as a temporary array.
public String[] getNames()
{
return getNamesRecursively( names, 0, TAB, 0 );
}
private static String[] getNamesRecursively( StringBuilder str, int pos, String delimiter, int cnt )
{
int end = str.indexOf( delimiter, pos );
String[] res;
if( end >= 0 )
res = getNamesRecursively( str, end + delimiter.length(), delimiter, cnt + 1 );
else
{
res = new String[ cnt + 1 ];
end = str.length();
}
res[ cnt ] = str.substring( pos, end );
return res;
}
![jacknad](https://i.stack.imgur.com/hgGkk.png?s=256&g=1)
jacknad
Electrical Engineer with experience in microprocessor hardware design, ASM, PL/M, C/C++, C#, Android, Linux, Python, and Java. First high school radio design burst into flames during the demo. First software program was FORTRAN on punch cards. Worked in FL, IL, ND, NJ, TX, VA, and WA.
Updated on July 09, 2022Comments
-
jacknad almost 2 years
The following code sort of works, but fixes the number of elements in String[]. Is there a way to make a String[] add the number of elements needed dynamically?
private static StringBuilder names = new StringBuilder(); ... public String[] getNames() { int start = 0; int end = 0; int i = 0; String[] nameArray = {"","","",""}; while (-1 != end) { end = names.indexOf(TAB, start); nameArray[i++] = names.substring(start, end); start = ++end; // The next name is after the TAB } return nameArray; }
-
Pablo Santa Cruz almost 14 yearsMy answer is doomed! Great @JonSkeet answered three seconds before I did. :-) Read your book Jon. It's awesome.
-
Stephen C almost 14 yearsImpractical. If the input StringBuilder is big enough, you'll overflow the stack.
-
jacknad almost 14 yearsPerfect! Only needed this one line. And yes, TAB is \t. Thanks a million.