how to convert NSString to NSArray
本问题已经有最佳答案,请猛点这里访问。
我有一根绳子
1 | NSString* str = @"[90, 5, 6]"; |
我需要把它转换成类似
1 | NSArray * numbers = [90, 5 , 6]; |
我这样做了很长一段时间:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | + (NSArray*) stringToArray:(NSString*)str { NSString *sep = @"[,"; NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:sep]; NSArray *temp=[str componentsSeparatedByCharactersInSet:set]; NSMutableArray* numbers = [[NSMutableArray alloc] init]; for (NSString* s in temp) { NSNumber *n = [NSNumber numberWithInteger:[s integerValue]]; [numbers addObject:n]; } return numbers; } |
有没有什么简洁快速的方法来进行这种转换?
谢谢
第一remove的unwanted个字符从字符串,像白色的空间和braces: P / < >
1 2 3 4 5 | NSString* str = @"[90, 5, 6]"; NSCharacterSet* characterSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789,"] invertedSet]; NSString* newString = [[str componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:@""]; |
你会有一个像这样的字符串:
1 2 3 4 5 | NSArray* arrayOfStrings = [newString componentsSeparatedByString:@","]; NSMutableArray* arrayOfNumbers = [NSMutableArray arrayWithCapacity:arrayOfStrings.count]; for (NSString* string in arrayOfStrings) { [arrayOfNumbers addObject:[NSDecimalNumber decimalNumberWithString:string]]; } |
使用"
1 2 | NSArray* arrayOfStrings = [newString componentsSeparatedByString:@","]; NSArray* arrayOfNumbers = [arrayOfStrings valueForKey: @"decimalNumberValue"]; |
1 2 3 4 5 | NSString* str = @"[90, 5, 6]"; NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"[]"]; NSArray *array = [[[str componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:@""] componentsSeparatedByString:@","]; |
1 2 3 4 5 | NSString *newSTR = [str stringByReplacingOccurrencesOfString:@"[" withString:@""]; newSTR = [newSTR stringByReplacingOccurrencesOfString:@"]" withString:@""]; NSArray *items = [newSTR componentsSeparatedByString:@","]; |
你可以实现,使用定期expression P / < >
((0 9)+) P / < >
1 2 3 4 | NSError* error = nil; NSString* str = @"[90, 5, 6]"; NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"([0-9]+)" options:0 error:&error]; NSArray* matches = [regex matchesInString:str options:0 range:NSMakeRange(0, [str length])]; |
然后你有nsarray的字符串,你就需要iterate它和convert的字符串插入到数量和他们中的一个阵列。 P / < >
像这样的尝试 P / < >
1 | NSArray *arr = [string componentsSeparatedByString:@","]; |