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

安稳与你 提交于 2019-12-04 02:53:26

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

You can use String's method split to do that in one line.

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;
}

String myLocation = builder.toString();

Tuhin
StringBuilder t= new StringBuilder();

String s= t.toString();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!