我有一个由三个字符串组成的字符串,如
NSString *first = ..;
NSString *second = ..;
NSString *third = ..;
NSString joinedString;
joinedString = [NSString stringWithFormat:@"%@ - %@ (%@)", first, second, third];
现在我需要从joinedString
取回三个原始字符串。我已经读过某个地方,我应该使用NSScanner
。任何想法如何起作用?
答案 0 :(得分:3)
根据您在问题中提供的示例,您可以执行以下操作:
// characters we are going to split at
NSString *sep = @" -()";
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:sep];
NSArray *strings = [joinedString componentsSeparatedByCharactersInSet:set];
// This is the simple way provided that the strings doesn't have spaces in them.
我会将NSScanner用于具有可变信息的较大字符串,并且您希望在大海捞针中找到该针。
答案 1 :(得分:1)
如果您获得了帖子中提到的确切模式,则可以使用NSRegularExpression(iOS 4 +):
NSString *regexStr = @"(.*)\s-\s(.*)\s\((.*)\)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:nil];
NSArray *results = [regex matchesInString:joinedString options:0 range:NSMakeRange(0, [joinedString length])];
NSString *string1 = [results objectAtIndex:0];
...
(没有错误处理,现在无法验证)
答案 2 :(得分:1)
您可以使用componentsSeparatedByCharactersInSet:
:
NSString *chars = @"-()";
NSArray *split = [joinedString componentsSeparatedByCharactersInSet:[NSCharacterset characterSetWithCharactersInString:chars]];
然后您可以修剪开始/结束空格:
stringFromArray = [stringFromArray stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];