2011-11-19 46 views
2

我想提取NSarray的所有「女兒」。ios如何提取for循環中的數組的所有rangeOfString?

例如,NSArray中作出這樣的:

hello 
hi 
hello daughter 
my goodness 
daughter (someone) 
my daughter 
how are you? 
etc. 

而且我想提取包含「女兒」的所有行。你能指出我正確的方向嗎?

我當前的代碼是:

for (NSString *mystring in self.array) 
{ 
    if ([mystring rangeOfString:searchText].location!=NSNotFound) 

{ 
    NSUInteger idx = [self.array indexOfObject:mystring]; 
    [self.filterarray addObject: mystring]; 
} 
} 

回答

3
NSArray *lines = ...; 
NSArray *filteredLines = [lines filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSString *string, NSDictionary *bindings) { 
    return ([string rangeOfString:searchText].location != NSNotFound); 
}]]; 

(需要iOS 4.0或更高版本)

如果需要支持較早的系統版本使用:

NSArray *lines = ...; 
NSArray *filteredLines = [lines filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(SELF contains[c] %@)", searchText]]; 

(需要iOS 3.0或更高版本)

+0

什麼是最低ios? – wagashi

+0

自從iOS 4.0以來,自3.0 iOS和predicateWithBlock:開始存在'filteredArrayUsingPredicate:'。 – Regexident

+0

self.filterarray是一個nsmutablearray,如何使用代碼添加對象到它?我寫了'\t self_filterarray = [self.array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^ BOOL(id string,NSDictionary * bindings){\t return([string rangeOfString:searchText] .location!= NSNotFound); \t}]];'warnings:incompatible Objective-C types'struct NSArray *',expected'struct NSMutableArray *',當傳遞參數1的'setFilteredListContent:'從不同的Objective-C類型 – wagashi

0
NSString *textViewText = @「hello hi hello daughter my goodness daughter (someone) my daughter how are you? etc.」; 

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:textViewText]; 


NSArray *highlightWords = @[@「daughter」,@」hello」]; 

for(NSString *word in highlightWords) 
{ 
    NSRange range = NSMakeRange(0, textViewText.length); 
    do{ 
     range = [textViewText rangeOfString:word options:NSCaseInsensitiveSearch range:range]; 
     [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range]; 
     if (range.location != NSNotFound) 
      range = NSMakeRange(range.location + 1, textViewText.length - (range.location + 1)); 
    }while(range.location != NSNotFound); 

}