如何使用rangeOfString
搜索大写和小写的字符串?
这是我到目前为止所拥有的;
for (NSString* key in words) {
if ([searchfield.text rangeOfString:key].location != NSNotFound)
{
NSString *textresult = [words objectForKey:key];
NSLog(@"Answer: %@", textresult);
result.text = textresult;
result.tag = 1;
}
由于
答案 0 :(得分:2)
只需在大写或小写中搜索相应的key
:
[searchField.text rangeOfString:[key lowercaseString]].location != NSNotFound
和
[searchField.text rangeOfString:[key uppercaseString]].location != NSNotFound
如果您不关心用户是使用大写还是小写,只需使用NSCaseInsensitiveSearch
选项:
[searchfield.text rangeOfString:key options: NSCaseInsensitiveSearch].location
!= NSNotFound
答案 1 :(得分:0)
我会使用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]);
}
}
答案 2 :(得分:0)
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
flavourarray = [[NSMutableArray alloc]init];
imagearray = [[NSMutableArray alloc]init];
categoryarray = [[NSMutableArray alloc]init];
[filteredListContent removeAllObjects]; // clear the filtered array first
searchText=[searchText uppercaseString];
NSString *cellTitle;
BOOL flag1=NO;
searchText=[searchText lowercaseString];
int i1=0;
j=0;
for (cellTitle in listContent)
{
NSComparisonResult result = [cellTitle compare:searchText
options:NSCaseInsensitiveSearch range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame)
{
if(flag1==NO)
{
filtered_flag=i1;
flag1=YES;
}
[filteredListContent addObject:cellTitle];
NSString *searchflavour = [[categoryarray_ipad objectAtIndex:j]objectForKey:@"flavour"];
NSString *searchcategory = [[categoryarray_ipad
objectAtIndex:j]objectForKey:@"category"];
NSString *searchimage = [[categoryarray_ipad objectAtIndex:j]objectForKey:@"image"];
if (searchText.length !=0) {
[categoryarray addObject:searchcategory];
}
[flavourarray addObject:searchflavour];
[imagearray addObject:searchimage];
}
j++;
i1++;
}
NSLog(@"filtered_flag:%d",filtered_flag);
NSLog(@"filtered:%@",filteredListContent);
searchresult =TRUE;
[itemstable_ipad reloadData];
}