2010-08-12 60 views
9

以下代码的工作类型,但修复了String []中元素的数量。有没有办法让一个String []添加动态需要的元素数量?如何最好地将StringBuilder转换为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; 
} 
+0

如果你想解释文字是如何被分解的话,那真的很有帮助。我已经根据代码做出了假设,但描述本来很好。 – 2010-08-12 21:36:39

回答

20

所以,你只是试图拆分选项卡?如何:

return names.toString().split(TAB); 

注意split需要一个正则表达式模式 - 所以不要指望split(".")只拆分上的点,例如:)

+6

我的回答注定了!大@JonSkeet在我做之前三秒钟回答。 :-) 读你的书乔恩。这很棒。 – 2010-08-12 21:38:26

+2

完美!只需要这一行。是的,TAB是\ t。太感谢了。 – jacknad 2010-08-14 13:24:44

2

您可以使用字符串的方法split做,在一个线。

4

要动态增长阵列,请使用ArrayList<String>,如果这是您的API需要的,您甚至可以将结果转换为String[]

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() ]); 

这就是说,你的目的使用split他人

+0

非常感谢!大的帮助。 – jacknad 2010-08-13 10:40:22

1

您可以使用递归实现使用程序堆栈作为临时数组的建议。

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

不切实际。如果输入的StringBuilder足够大,则会溢出堆栈。 – 2010-08-12 22:47:46

-4
StringBuilder t= new StringBuilder(); 

String s= t.toString(); 
0

字符串myLocation = builder.toString();

相关问题