我会使用 NSRange 和 [NSString lowercaseString] 创建搜索字符串和要搜索的单词的小写版本。
然后使用小写搜索字符串的 rangeOfString 方法生成一个 NSRange,然后我会使用“successRange”来输出相应的原始文本块。
这是我为您准备的一个工作示例:
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", @"key3", @"key4", @"key5",@"key6", nil];
NSArray *objects = [NSArray arrayWithObjects:@"How", @"are", @"you", @"doing", @"?",@"How are you doing?", nil];
NSDictionary * words = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString * searchString = @"are";
NSString * lowercaseSearchString = [searchString lowercaseString];
for(NSString * key in words){
NSString * text = [words objectForKey:key];
NSString * lowercaseText = [text lowercaseString];
NSRange successRange = NSRangeFromString(@"");
NSRange lowercaseRange = [lowercaseText rangeOfString:lowercaseSearchString];
if(lowercaseRange.location!=NSNotFound){
successRange = lowercaseRange;
}
NSLog(@"key: %@, text: %@", key,text);
if(successRange.length >0){
NSLog(@" text subStringWithRange: %@", [text substringWithRange:successRange]);
}
}