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

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

4

2 回答 2

3
NSArray *words = [str componentsSeparatedByString:@" "];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH %@", @"at"];
NSArray *wordsStartingWithAt = [words filteredArrayUsingPredicate:predicate];
于 2012-09-23T12:55:29.413 回答
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);
}];
于 2012-09-23T12:58:45.623 回答