1

I have a for loop which loops through an array and want to match a search field's text to an object in the array.

I have the following code

for (int i = 0; i < [data2 count]; i++) {
    if ([data2 objectAtIndex:i] == searchField.text) {
        NSLog(@"MATCH");
            break;
    }
}

I know in Java it can be done by e.g. if(searchField.text.equalsIgnoreCase(the object to match against))

How is this done in objective C, to match the string without case?

Also, what if I wanted to match part of the string, would that be done in Obj C char by char or is there a built in function for matching parts of Strings?

Thanks

G.Y
  • 6,042
  • 2
  • 37
  • 54
some_id
  • 29,466
  • 62
  • 182
  • 304
  • 1
    Pretty close to: [Understanding NSString comparison in Objective-C ](http://stackoverflow.com/questions/3703554/understanding-nsstring-comparison-in-objective-c), but you want `caseInsensitiveCompare:`. – Carl Norum Sep 27 '10 at 06:37

3 Answers3

4

Assuming your strings are NSStrings, you can find your answers at the NSString Class Reference

NSString supports caseInsensitiveCompare: and rangeOfString: or rangeOfString:options: if you want a case insensitive search.

The code would look like this:

if (NSOrderedSame == [searchField.text caseInsensitiveCompare:[data2 objectAtIndex:i]) {
    // Do work here.
}
Kris Markel
  • 12,142
  • 3
  • 43
  • 40
3
[[data2 objectAtIndex:i] isEqualToString: searchField.text]
RolandasR
  • 3,030
  • 2
  • 25
  • 26
2

You use isEqual: (to compare objects in general) or isEqualToString: (for NSStrings specifically). And you can get substrings with the substringWithRange: method.

Chuck
  • 234,037
  • 30
  • 302
  • 389