从NSString中提取字符串

时间:2012-09-23 12:48:49

标签: objective-c cocoa nsstring

NSString *str = [NSString stringWithString:@"The dog ate the cat"];

如何从上面以“at”开头的字符串中提取单词。

2 个答案:

答案 0 :(得分:3)

NSArray *words = [str componentsSeparatedByString:@" "];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH %@", @"at"];
NSArray *wordsStartingWithAt = [words filteredArrayUsingPredicate:predicate];

答案 1 :(得分:1)

您需要使用NSRegularExpression类。

NSString *str = @"The dog ate the cat";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:@"(at\\w+)"
                              options:NSRegularExpressionCaseInsensitive
                              error:&error];
[regex enumerateMatchesInString:str options:0
                          range:NSMakeRange(0, str.length)
                     usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop)
{
    NSString *result = [str substringWithRange:match.range];
    NSLog(@"%@", result);
}];