在for循环中附加NSMutable Strings

时间:2012-06-13 05:56:13

标签: iphone ios objective-c

//viewdidload
{
str1 = [[NSMutableString alloc] initWithCapacity:0];
str2 = [[NSMutableString alloc] initWithCapacity:0];
}//

for (int pq=1; pq<=temp; pq++) 
{
str1 =  [NSMutableString stringWithString:[documentManager wholeTextForPage:pq] ] ;
[self.str2 appendString:str1];
NSLog(@"content of page chumma1:  %@",str1);
}
NSLog(@"cwhole text:  %@",str2

**这里str1在每次迭代时返回不同的字符串。我试图将str1返回的每个字符串附加到str2。但str2在第一次迭代时只返回str1返回的一个字符串。其他迭代返回的字符串不会附加到str2。请帮助我找到一种方法来解决这个问题。提前致谢。

谢谢&amp;问候 VEERA **

5 个答案:

答案 0 :(得分:0)

Use stringByAppendingString see example:
But str2 should declare NSString

<强>更新

NSMutableString *str1 = [NSMutableString string];
NSString *str2 = @"";

for (int pq=1; pq<=temp; pq++) 
{
    str1 =  [NSMutableString stringWithString:[documentManager wholeTextForPage:pq] ] ;
    str2 = [str2 stringByAppendingString:str1];
}

这会将所有数据从str1追加到str2。

答案 1 :(得分:0)

尝试这样的事情......

....
for (int pq=0; pq < temp; pq++)  {
    str1 =  [NSMutableString stringWithString:[documentManager wholeTextForPage:pq] ] ;
    [self.str2 appendString:str1];
    NSLog(@"content of page chumma1:  %@",str1);
}

NSLog(@"cwhole text:  %@",str2

答案 2 :(得分:0)

这样做是为了追加字符串:

str1 = [[NSMutableString alloc] initWithCapacity:0];
for (int pq=1; pq<=temp; pq++) 
{
  str1 = [str1 stringByAppendingString:[NSString stringWithString:[documentManager wholeTextForPage:pq]]];
}

答案 3 :(得分:0)

NSMutableString *str1= [NSMutableString new];
    for (int i =0; i < 10; i++) {
        [str1 appendString:@"Hi "];
    }   
    NSLog(@"%@",str1);

您的代码可能无效,因为appendString:(NSString *)str不是NSMutableString。所以使用NSString。

代码试试这个

for (int pq=1; pq<=temp; pq++)
    [self.str2 appendString:[documentManager wholeTextForPage:pq]];

答案 4 :(得分:0)

以这种方式尝试......

NSMutableString *str1 = [[NSMutableString alloc]initWithCapacity:0];
NSMutableString *str2 = [[NSMutableString alloc]initWithCapacity:0];

for(int pq=1; pq<temp; pq++)
{
    str1 = [NSMutableString stringWithFormat:[documentManager wholeTextForPage:pq]];
    str2 = (NSMutableString *)[str2 stringByAppendingFormat:str1];
    NSLog(@"content of page chumma1:  %@",str1);
}

NSLog(@"cwhole text:  %@",str2);