从字符串到数组的内容

时间:2011-08-18 12:05:54

标签: objective-c

我有一个需要排序的字符串(不是从高到低),字符串设置为用逗号分隔每个数字,每隔三个数字后面一个空格:

  

26,2496,1492252306 1049,99,68353132 860,99,59587920 4717,99,43863427 807,99,67243688 1382,99,37865117 1088,99,14810482 95,99,67711274 5,99,200000000 3310, 99,25639438 75,99,157217334 1923,99,29678736 48,99,118806349 133,99,35055345 563,99,21098356 3410,99,17805574 47,99,62821143 2504,99,14821240 5,99,200000000 3076, 99,19425499 474,99,31321799 3983,99,16825678 17826,99,13768252 1129,99,17249030 5393,99,14082021 338,120,137201472 2850,1944 -1,-1 -1,-1 -1,-1 - 1,-1 4509,3988 3863,3987 2632,4148 5790,4105 -1,-1 -1,-1

我需要为3个数字中的每一个创建某种关联。有点像2d数组和字典的东西。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

假设您的字符串保存在名为“myNumbers”的变量中,请执行以下操作:

NSString *myNumbers = @"26,2496,1492252306 1049,99,68353132 860,99,59587920 4717,99,43863427 807,99,67243688 1382,99,37865117 1088,99,14810482 95,99,67711274 5,99,200000000 3310,99,25639438 75,99,157217334 1923,99,29678736 48,99,118806349 133,99,35055345 563,99,21098356 3410,99,17805574 47,99,62821143 2504,99,14821240 5,99,200000000 3076,99,19425499 474,99,31321799 3983,99,16825678 17826,99,13768252 1129,99,17249030 5393,99,14082021 338,120,137201472 2850,1944 -1,-1 -1,-1 -1,-1 -1,-1 4509,3988 3863,3987 2632,4148 5790,4105 -1,-1 -1,-1";

NSArray *triples = [myNumbers componentsSeparatedByString:@" "];

NSMutableArray *matrix = [[NSMutableArray alloc] init];

for (NSString *triple in triples) {
    [matrix addObject:[triple componentsSeparatedByString:@","]];
}

NSLog(@"matrix: %@", matrix);
[matrix release];

答案 1 :(得分:0)

如何首先用空格分割字符串,然后用逗号分割每个分割的项目,如下面的算法?

threeItems = split main string with white space
for each itemString in threeItems
  threeItem = split itemString with comma
  do something with threeItem
end for