views:

75

answers:

3

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

+2  A: 
[[data2 objectAtIndex:i] isEqualToString: searchField.text]
GameBit
This comparison would be case sensitive.
Robot K
+3  A: 

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.
}
Robot K
+2  A: 

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

Chuck