NSString *numberVector = @"( 1, 2, 3, 4)";
我想从这些数字中获取 NSMutableArray。我怎样才能做到这一点?
NSString *numberVector = @"( 1, 2, 3, 4)";
我想从这些数字中获取 NSMutableArray。我怎样才能做到这一点?
这是更简单的一个,先将其转换为 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 或其他可用的解析库。
如果您知道这正是您的格式,并且不必在空格、括号或逗号的数量上保持灵活:
NSCharacterSet *trimSet = [NSCharacterSet characterSetWithCharactersInString:@" ()"];
numberVector = [numberVector stringByTrimmingCharactersInSet:trimSet];
NSArray *numbers = [numberVector componentsSeparatedByString:@", "];
像这样尝试它对于它只接受数字的任何类型的数据都可以正常工作。
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);
请参阅下面的代码,它应该可以工作:
NSCharacterSet *cSet = [NSCharacterSet characterSetWithCharactersInString:@" ()"];
numberVector = [numberVector stringByTrimmingCharactersInSet:cSet];
//specify delimiter below
NSArray *numbers = [numberVector componentsSeparatedByString:@", "];
有了这个:
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:@", "]