1
NSString *numberVector = @"( 1, 2, 3, 4)";

我想从这些数字中获取 NSMutableArray。我怎样才能做到这一点?

4

5 回答 5

3

这是更简单的一个,先将其转换为 json 字符串,然后转换为数组使用NSJSONSerialization

NSString *numberVector = @"( 1, 2, 3, 4)";
numberVector = [numberVector stringByReplacingOccurrencesOfString:@"(" withString:@"["];
numberVector = [numberVector stringByReplacingOccurrencesOfString:@")" withString:@"]"];
NSError* error;
NSMutableArray *arr = [NSJSONSerialization JSONObjectWithData:[numberVector dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];

更新

这对两者都有效@"( 1, 2, 3, 4)"@"(\n 1,\n 2,\n 3,\n 4\n)"因为 json 字符串可以有新行和空格。

PS这适用于 iOS 5.0 或更高版本的其他 iOS,您可以使用 SBJSON 或其他可用的解析库。

于 2013-03-20T14:33:39.923 回答
1

如果您知道这正是您的格式,并且不必在空格、括号或逗号的数量上保持灵活:

NSCharacterSet *trimSet = [NSCharacterSet characterSetWithCharactersInString:@" ()"];
numberVector = [numberVector stringByTrimmingCharactersInSet:trimSet];
NSArray *numbers = [numberVector componentsSeparatedByString:@", "];
于 2013-03-20T14:21:41.527 回答
1

像这样尝试它对于它只接受数字的任何类型的数据都可以正常工作。

NSString *numberVector = @"(\n 1,\n 2,\n 3,\n 4\n)";

    NSString *onlyNumbers = [numberVector  stringByReplacingOccurrencesOfString:@"[^0-9,]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [numberVector  length])];
    NSArray *numbers=[onlyNumbers componentsSeparatedByString:@","];
    NSLog(@"%@",numbers);
于 2013-03-20T14:37:25.237 回答
0

请参阅下面的代码,它应该可以工作:

  NSCharacterSet *cSet = [NSCharacterSet characterSetWithCharactersInString:@" ()"];  
  numberVector = [numberVector stringByTrimmingCharactersInSet:cSet];
  //specify delimiter below
  NSArray *numbers = [numberVector componentsSeparatedByString:@", "];
于 2013-03-20T14:28:22.740 回答
-2

有了这个:

NSString *numberVector = @"( 1, 2, 3, 4)";

编辑

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"&([^;])*;" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [numberVector stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];

NSArray *listItems = [[modifiedString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsSeparatedByString:@", "]
于 2013-03-20T14:20:30.327 回答