Java 如何将 StringBuilder 最好地转换为 String[]?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3472234/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can a StringBuilder best be converted to a String[]?
提问by Hymannad
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?
以下代码可以正常工作,但修复了 String[] 中元素的数量。有没有办法让 String[] 添加动态所需的元素数量?
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;
}
采纳答案by Jon Skeet
So you're just trying to split on tab? How about:
所以你只是想在选项卡上拆分?怎么样:
return names.toString().split(TAB);
Note that splittakes a regular expression pattern - so don't expect split(".")to split just on dots, for example :)
请注意,split它采用正则表达式模式 - 因此不要期望split(".")仅在点上拆分,例如 :)
回答by Pablo Santa Cruz
回答by Alexander Pogrebnyak
To dynamically grow array, use ArrayList<String>, you can even convert the result to String[]if that's what your API requires.
要动态增长数组,请使用ArrayList<String>,您甚至可以将结果转换为String[]您的 API 要求的结果。
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 splitas suggested by others
也就是说,出于您的目的,请split按照其他人的建议使用
回答by x4u
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;
}
回答by Tuhin
StringBuilder t= new StringBuilder();
String s= t.toString();
回答by Ashwin H
String myLocation = builder.toString();
String myLocation = builder.toString();

