2

我有一个像这样由三个字符串组成的字符串

NSString *first = ..;
NSString *second = ..;
NSString *third = ..;

NSString joinedString;
joinedString = [NSString stringWithFormat:@"%@ - %@ (%@)", first, second, third];

现在我需要从joinedString. 我已经在某个地方读过我应该NSScanner为此使用的地方。任何想法如何工作?

4

3 回答 3

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 与具有可变信息的较大字符串一起使用,并且您想在大海捞针中找到那根针。

于 2011-03-28T12:24:47.437 回答
1

您可以使用componentsSeparatedByCharactersInSet:

NSString *chars = @"-()";
NSArray *split = [joinedString componentsSeparatedByCharactersInSet:[NSCharacterset characterSetWithCharactersInString:chars]];

然后,您可以修剪开始/结束空格:

stringFromArray = [stringFromArray stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
于 2011-03-28T12:40:56.870 回答
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];
...

(没有错误处理,现在无法验证)

于 2011-03-28T12:36:54.063 回答