Case insensitive comparison NSString

后端 未结 12 1596
滥情空心
滥情空心 2020-12-12 13:15

Can anyone point me to any resources about case insensitive comparison in Objective C? It doesn\'t seem to have an equivalent method to str1.equalsIgnoreCase(str2)

相关标签:
12条回答
  • 2020-12-12 13:38

    Try this method

    - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
    
    0 讨论(0)
  • 2020-12-12 13:39

    A new way to do this. iOS 8

    let string: NSString = "Café"
    let substring: NSString = "É"
    
    string.localizedCaseInsensitiveContainsString(substring) // true
    
    0 讨论(0)
  • 2020-12-12 13:41

    to check with the prefix as in the iPhone ContactApp

    ([string rangeOfString:prefixString options:NSCaseInsensitiveSearch].location == 0)
    

    this blog was useful for me

    0 讨论(0)
  • 2020-12-12 13:44
    NSMutableArray *arrSearchData;  
    NSArray *data=[arrNearByData objectAtIndex:i];
    NSString *strValue=[NSString stringWithFormat:@"%@", [data valueForKey:@"restName"]];
    NSRange r = [strValue rangeOfString:key options:NSCaseInsensitiveSearch];
    
    if(r.location != NSNotFound)
    {
         [arrSearchData addObject:data];
    }
    
    0 讨论(0)
  • 2020-12-12 13:49

    You could always ensure they're in the same case before the comparison:

    if ([[stringX uppercaseString] isEqualToString:[stringY uppercaseString]]) {
        // They're equal
    }
    

    The main benefit being you avoid the potential issue described by matm regarding comparing nil strings. You could either check the string isn't nil before doing one of the compare:options: methods, or you could be lazy (like me) and ignore the added cost of creating a new string for each comparison (which is minimal if you're only doing one or two comparisons).

    0 讨论(0)
  • 2020-12-12 13:51
    if( [@"Some String" caseInsensitiveCompare:@"some string"] == NSOrderedSame ) {
      // strings are equal except for possibly case
    }
    

    The documentation is located at Search and Comparison Methods

    0 讨论(0)
提交回复
热议问题