Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a StringBuilder best be converted to a String[]?

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;
}
like image 413
jacknad Avatar asked Aug 12 '10 21:08

jacknad


People also ask

Can StringBuilder be converted to string?

There is no such thing as a StringBuilder to String conversion. StringBuilder class provides you with a toString method which allows you to get the string which is actually stored in the internal buffer of the StringBuilder object. String s = sb.

How can we convert string to StringBuilder select one?

Note: You can use any String method on a StringBuilder object by first converting the string builder to a string with the toString() method of the StringBuilder class. Then convert the string back into a string builder using the StringBuilder(String str) constructor.

How do you get string out of StringBuilder?

You can use . ToString() to get the String from the StringBuilder .

What method is used to concatenate a string to a StringBuilder object?

String concatenation using StringBuilder class StringBuilder is class provides append() method to perform concatenation operation. The append() method accepts arguments of different types like Objects, StringBuilder, int, char, CharSequence, boolean, float, double.


2 Answers

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 :)

like image 149
Jon Skeet Avatar answered Oct 05 '22 22:10

Jon Skeet


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

like image 25
Alexander Pogrebnyak Avatar answered Oct 06 '22 00:10

Alexander Pogrebnyak