NSString *numberVector = @"( 1, 2, 3, 4)";
我想从这些数字中获取NSMutableArray。 我怎么能这样做?
答案 0 :(得分: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字符串可以有新的行和空格。
P.S 这适用于其他iOS的iOS 5.0或更高版本,您可以使用SBJSON或其他可用的解析库。
答案 1 :(得分:1)
如果您知道这正是您的格式,并且不必在空格,括号或逗号的数量上保持灵活性:
NSCharacterSet *trimSet = [NSCharacterSet characterSetWithCharactersInString:@" ()"];
numberVector = [numberVector stringByTrimmingCharactersInSet:trimSet];
NSArray *numbers = [numberVector componentsSeparatedByString:@", "];
答案 2 :(得分: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);
答案 3 :(得分:0)
请参阅下面的代码,它应该有效:
NSCharacterSet *cSet = [NSCharacterSet characterSetWithCharactersInString:@" ()"];
numberVector = [numberVector stringByTrimmingCharactersInSet:cSet];
//specify delimiter below
NSArray *numbers = [numberVector componentsSeparatedByString:@", "];
答案 4 :(得分:-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:@", "]