我想解析NSArray的NSString,但無法獲得任何成功。這是我的字符串:NSString *points = @"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
解析NSString到NSArray
我想這個字符串映射到NSArray。
NSArray *tempArray = points;
我想解析NSArray的NSString,但無法獲得任何成功。這是我的字符串:NSString *points = @"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
解析NSString到NSArray
我想這個字符串映射到NSArray。
NSArray *tempArray = points;
OK,代碼高爾夫(未經測試):
NSString *points = @"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
NSError *error = nil;
NSArray *pointsArray = [NSJSONSerialization JSONObjectWithData:[points dataUsingEncoding:NSUTF8StringEncoding]
options:kNilOptions
error:&error];
for (NSArray *point in pointsArray) {
NSAssert([point count] == 2, @"Invalid point");
// do thing with point
CGPoint pt = CGPointMake([point[0] floatValue], [point[1] floatValue]);
}
太棒了。你搖滾:) – Idrees
你能PLZ試試這個,它可以解決你的問題,
NSString *points = @"[[51.471914582, -0.12274114637],[51.47287707533, -0.12163608379]]";
NSArray* arrayOfStrings = [points componentsSeparatedByString:@","];
NSLog(@"%@",arrayOfStrings);
NSMutableArray *copyArray = [arrayOfStrings mutableCopy];
NSMutableString *stringFirst = (NSMutableString *)[copyArray objectAtIndex:0];
NSMutableString *stringLast = (NSMutableString *)[copyArray lastObject];
stringFirst=[stringFirst substringFromIndex:1];
stringLast=[stringLast substringToIndex:stringLast.length-1];
[copyArray replaceObjectAtIndex:0 withObject:stringFirst];
[copyArray replaceObjectAtIndex:(copyArray.count-1) withObject:stringLast];
NSMutableArray *yourarray = [[NSMutableArray alloc] init];
for (int i=0; i<=(copyArray.count/2); i+=2) {
[yourarray addObject:[NSString stringWithFormat:@"%@,%@",[copyArray objectAtIndex:i], [copyArray objectAtIndex:i+1]]];
}
NSLog(@"%@",yourarray);
編碼愉快!
該字符串看起來像JSON這樣你就可以使用NSJSONSerialization
NSData * data = [points dataUsingEncoding: NSUTF8StringEncoding];
NSError * error = nil;
NSArray * arrayOfPointArrays = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
'componentsSeparatedByString','stringByReplaceingString',正則表達式等什麼有你試過嗎? – Larme
試試這個:NSArray * arrayOfStrings = [points componentsSeparatedByString:@「,」]; – Tanuj
@Idrees實際上是JSON格式的字符串嗎? – trojanfoe