some_id
some_id

Reputation: 29886

Matching Strings in Objective C

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

Upvotes: 1

Views: 3694

Answers (3)

Kris Markel
Kris Markel

Reputation: 12112

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.
}

Upvotes: 4

Chuck
Chuck

Reputation: 237010

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

Upvotes: 2

RolandasR
RolandasR

Reputation: 3047

[[data2 objectAtIndex:i] isEqualToString: searchField.text]

Upvotes: 3

Related Questions