2012-09-23 105 views
-3
NSString *str = [NSString stringWithString:@"The dog ate the cat"]; 

如何從上面的字符串中提取以「at」開頭的字符。從NSString中提取字符串

+0

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html – 2012-09-23 12:51:39

+0

如何更精確:鏈接的頁面擁有1000萬行 –

+2

@M Holod鍵盤上有「選項」和「F」鍵...... – 2012-09-23 12:56:13

回答

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); 
}]; 
3
NSArray *words = [str componentsSeparatedByString:@" "]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH %@", @"at"]; 
NSArray *wordsStartingWithAt = [words filteredArrayUsingPredicate:predicate];