如何在字符串操作时获取 ios 中某些特殊字符之间的数据

how to get data between some special characters in ios while string manipulation

我正在尝试从字符串中获取子字符串。这是我的代码:

NSString *haystack = @"1:ketan jogal:1 2:ios developer:2";

NSString*p1=@"1:";
NSString*s1=@":1";

NSString *prefix = @"2:";
NSString *suffix = @":2"; 

NSRange needleRange = NSMakeRange(prefix.length,
                                  haystack.length - prefix.length - suffix.length);
NSRange needlerange1=NSMakeRange(p1.length,
                                  haystack.length - prefix.length - s1.length);


NSString *needle = [haystack substringWithRange:needleRange];
NSString*needle1=[haystack substringWithRange:needlerange1];

NSLog(@"needle1: %@",needle1);
NSLog(@"needle: %@", needle); 

但我每次都无法得到这样的输出。

2015-01-31 17:07:44.119 WriteintoTextFile[1685:60b] needle1: ketan jogal:1 2:ios developer

能否请您建议我如何获取此类数据?

您可以通过两种方式实现:

1

使用NSString

componentsSeparatedByString方法
NSString *haystack = @"1:ketan jogal:1 2:ios developer:2";
NSArray *arr       = [haystack componentsSeparatedByString:@":"];
NSLog(@"%@",arr[1]);
NSLog(@"%@",arr[3]);

2

使用NSScanner

NSScanner *scanner = [[NSScanner alloc] initWithString:haystack];
NSString *result   = nil;

[scanner scanUpToString:@"1:" intoString:nil];
[scanner scanString:@"1:" intoString:nil];
[scanner scanUpToString:@":1" intoString:&result];
NSLog(@"%@",result);

[scanner scanUpToString:@"2:" intoString:nil];
[scanner scanString:@"2:" intoString:nil];
[scanner scanUpToString:@":2" intoString:&result];
NSLog(@"%@",result);