2012-03-14 51 views
1

我有一个很大的stringbuffer,我想分成更小的部分。该字符串缓冲区看起来像这样将StringBuffer分成较小的部分

"name1+name2+name3+name4+..........+name2000" 

name1=john 
name2=prince 
and so on. 

(你得到idea.name1,NAME2,NAME3代表不同长度的实际名称)

现在我想用来存储字符串数组中的名称,每个位置包含200个名称。

string[0]="name1+name2+name3+........+name200"; 
string[1]="name201+name202+...." 

我将如何去实现这项任务?

+0

是在名字'StringBuffer'由','隔开? – noMAD 2012-03-14 05:31:34

+0

它们由“+”分隔。 – user1092042 2012-03-14 05:32:42

+1

到目前为止您尝试过什么?你尝试的解决方案的哪一部分是专门给你带来麻烦的? – maerics 2012-03-14 05:39:57

回答

2
StringTokenizer str = new StringTokenizer(<StringBufferObject>); 
int count = 0; 
int arrCount = 0; 
StringBuffer temp; 
String[] stringArr = new String[x]; 
while(str.hasMoreTokens()) { 
    count++; 
    if(count != 200) { 
     temp.append(str.nextToken()); 
    } 
    else { 
    stringArr[arrCount] = temp; 
    temp.delete(0,temp.length()); 
    count = 0; 
    arrCount++; 
} 
+0

得到它终于工作。谢谢。 – user1092042 2012-03-14 06:39:43

0

每个名称之间必须有一些分隔符。要打破字符串,我们应该有一些分隔符。 如果您有分隔符,您可以在for循环中使用subString()。

+0

如果您使用+作为分隔符,那么代码将如下所示: – 2012-03-14 05:43:44

0

尝试使用

String[] tempNames = new String(namesBuffer).split("+"); 

然后

int length = (tempNames.length/200)+ (tempName.length % 200) 
String[] names = new String[length]; 
for(int i = 0 ; i< tempNames.length ; i++){ 
    for(int j = 0 ; j < length ; j++) 
     names[j] = tempNames[i]; 
} 

希望这有助于在 “+”

+0

为什么'names [j] = tempNames [i]'?他需要将较小的数据块存储到名称字符串数组中,比如'names [0] = tempNames [0] +“+”+ tempNames [1] + ... + tempNames [199];'当您重写时名字[j](名字[0],名字[1] ...)为每个'我'迭代。 – 2012-03-14 06:04:51

+0

你是对的我必须但内部循环出来,反之亦然 – 2012-03-14 14:24:50

1

这将是一个更容易分裂使用String.split()如果可能的字符串:

/* something like this */ 

String arrayOfStrings = inputString.split("\+"); 

如果你要保持它作为一个StringBuffer,你必须循环输入并自己标记它。

我想这将是这个样子:

public String[] getTwoHundredStrings(StringBuffer inputBuff, String someToken) 
{ 
    String [] nameArray = new String [200]; 

    int currentPos = 0; 
    int nextPos = 0; 

    for (int i = 0; i < 200; i ++) { 

     nextPos = inputBuff.indexOf(someToken, currentPos); 

     if (nextPos < 0) { 
      break; 
     } 

     String nextName = inputBuff.substring(currentPos, nextPos); 

     nameArray[i] = nextName;   
     currentPos = nextPos; 
    } 

    /* do some cleanup if nameArray has less than 200 elements */ 

    return nameArray;