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;
}
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.
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.
You can use . ToString() to get the String from the StringBuilder .
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.
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 :)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With