一如既往,有很多方法可以做到這一點。
OPTION 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
)
注意
所有這些假設以及形成字符串,所以你應該包括你自己的錯誤檢查。
['NSRegularExpression'](http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html) – millimoose 2013-05-10 01:29:28
[NSScanner](https://developer.apple .com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSScanner_Class/Reference/Reference.html) – vikingosegundo 2013-05-10 01:51:15
我們的答案是否有助於您? – lnafziger 2013-05-24 20:20:02