Iphone 将垂直信息的NSString转换为多维数组-目标C

Iphone 将垂直信息的NSString转换为多维数组-目标C,iphone,objective-c,nsstring,nsarray,Iphone,Objective C,Nsstring,Nsarray,我有一系列的垂直信息,例如: “0.943182 0.95878 0.853249 0.956043 0.795583 0.954268 0.738116 0.954268 0” 我需要在每个值之间添加逗号,将顶点分成三组,然后将这三个值添加到一个数组中(然后将其添加到多维数组中,以便与OpenGL ES一起使用) 有人能告诉我如何插入逗号和分组数据吗 谢谢 我宁愿一步一步地扫描字符串,而不是先在字符串中插入逗号: NSString *str = @"0.943182 0.95878 0 0.8

我有一系列的垂直信息,例如:

“0.943182 0.95878 0.853249 0.956043 0.795583 0.954268 0.738116 0.954268 0”

我需要在每个值之间添加逗号,将顶点分成三组,然后将这三个值添加到一个数组中(然后将其添加到多维数组中,以便与OpenGL ES一起使用)

有人能告诉我如何插入逗号和分组数据吗


谢谢

我宁愿一步一步地扫描字符串,而不是先在字符串中插入逗号:

NSString *str = @"0.943182 0.95878 0 0.853249 0.956043 0 0.795583 0.954268 0 0.738116 0.954268 0";
NSScanner *scanner = [NSScanner scannerWithString:str];
typedef struct { float x, y, z; } vertex;
while (YES) {
    vertex v;
    if (! ([scanner scanFloat:&v.x] && [scanner scanFloat:&v.y] && [scanner scanFloat:&v.z]))
        break;
    NSLog(@"%f, %f, %f", v.x, v.y, v.z);
    // put the vertex in some container
}
相当简单:

断开绳子

NSArray *nums = [theString componentsSeparatedByString:@" "];
Alloc/init将存储组的组数组

NSMutableArray *groups = [NSMutableArray arrayWithCapacity:10];
在源字符串的组件上循环,并使用它们将组分隔为“
”、“

NSUInteger basetIndex = 0;
NSString *str = @"";
for(baseIndex = 0; baseIndex < [nums count]; baseIndex += 3) {
    str = [str stringByAppendingFormat:@"%@,%@,%@", [nums objectAtIndex:baseIndex],
                                       [nums objectAtIndex:baseIndex+1],
                                       [nums objectAtIndex:baseIndex+2]];
    [groups addObject:str];
    str = @"";
    // or str = [NSString stringWithFormat:...] and no str = @""
}
nsuiger basetIndex=0;
NSString*str=@;
对于(baseIndex=0;baseIndex<[nums计数];baseIndex+=3){
str=[str stringByAppendingFormat:@“%@,%@,%@”,[nums objectAtIndex:baseIndex],
[nums objectAtIndex:baseIndex+1],
[nums objectAtIndex:baseIndex+2];
[组addObject:str];
str=@;
//或str=[NSString stringWithFormat:…]且无str=@“”
}

如果给定正确数量的数字,此代码将正常工作,您可以在另一种情况下检查组件的索引。

请尝试以下解决方案

NSString *str  = @"0.943182 0.95878 0 0.853249 0.956043 0 0.795583 0.954268 0 0.738116 0.954268 0";
NSArray *arr = [str componentsSeparatedByString:@" "];
NSUInteger cnt = 0;
NSMutableArray *multilist = [[NSMutableArray alloc] init];
NSString *temp = @"";
for (NSString *comp in arr ) {

    cnt++;
    if( cnt == 3 )
    {
        cnt = 0;
        temp = [temp stringByAppendingFormat:@"%@" ,comp];
        [multilist addObject:temp];
        temp = @"";
    }
    else
    {
        temp = [temp stringByAppendingFormat:@"%@ ," ,comp];
    }
}
NSLog(@"%@",multilist);
[multilist release];

示例中有10个数字,因此最后一组只有一个数字?对于逗号,您可以使用[yourString StringByReplacingOfString:@”“withString:@”“,“]我得到的是“未找到格式的实例方法stringWithFormat”?谢谢更正!愚蠢的错误,前一个是类方法。还进行了轻微修改,以获得所需的行为