与往常一样,有很多方法可以做到这一点。
选项 1
如果这些是固定长度的字符串(每个部分总是三个字符),那么您可以直接获取子字符串:
NSString *sampleString = @"[abc]000";
NSString *left = [sampleString substringWithRange:NSMakeRange(1, 3)];
NSString *right = [sampleString substringWithRange:NSMakeRange(5, 3)];
NSArray *parts = @[ left, right ];
NSLog(@"%@", parts);
选项 1(缩短)
NSArray *parts = @[ [sampleString substringWithRange:NSMakeRange(1, 3)],
[sampleString substringWithRange:NSMakeRange(5, 3)] ];
NSLog(@"%@", parts);
选项 2
如果它们不总是三个字符,那么您可以使用NSScanner
:
NSString *sampleString = @"[abc]000";
NSScanner *scanner = [NSScanner scannerWithString:sampleString];
// Skip the first character if we know that it will always start with the '['.
// If we can not make this assumption, then we would scan for the bracket instead.
scanner.scanLocation = 1;
NSString *left, *right;
// Save the characters until the right bracket into a string which we store in left.
[scanner scanUpToString:@"]" intoString:&left];
// Skip the right bracket
scanner.scanLocation++;
// Scan to the end (You can use any string for the scanUpToString that doesn't actually exist...
[scanner scanUpToString:@"\0" intoString:&right];
NSArray *parts = @[ left, right ];
NSLog(@"%@", parts);
结果(所有选项)
2013-05-10 00:25:02.031 Testing App[41906:11f03] (
abc,
000
)
注意
所有这些都假设格式正确的字符串,所以你应该包括你自己的错误检查。