1

I would like to know how to compare a string with an array, i.e., if my array list has {"abc", "pqr", "xyz"} and the new string lets say "mno" is typed, it should compare with my previous array list. How can I do this? Thanks in advance.

4 Answers 4

9

Look at the NSArray documentation...

BOOL hasString = [your_array containsObject:your_string];
Sign up to request clarification or add additional context in comments.

4 Comments

can we use it in if condition
@sameer, yes you can: if ([your_array containsObject:your_string]) {}
This is only a good solution if you are not interested in the actual string contents - which is usually not the case. The containsObject call uses isEquals to compare each item.
@crow, you're the only one that took this into account. I was actually looking for a way to invoke isEqualToString in a similar way, but later realised that isEqual is enough for me in current scenario. However, I'm interested in a clean solution with isEqualToString, just out of curiosity. Do you know how we can achieve that?
2

System:

if ([yourArray containsObject:yourNSString])
{
    NSLog(@"Bingo!");
}

Manual:

for (int i = 0 ; i < [yourArray count] ; i++) {
    if ([yourNSString isEqualToString:[yourArray objectAtIndex:i]]) {
        NSLog(@"Bingo!");
        break;
    }
}

Comments

1
for(int i=0; i<[myarray length]; ++i) {
     if([myarray[i] isEqualToString:@"mno"])
            NSLog("Equal");
     else NSLog("Not Equal");
}

Comments

0

Here is a working (tested) method,

-(BOOL)checkStingInArray: (NSString *)aString arrayWithStrings:(NSMutableArray *)array

{

    if ( [array containsObject: aString] ) {

        NSLog(@" %@ found in Array",aString );
        return YES;

    } else {
        NSLog(@" %@ not found in Array",aString );
        return NO;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.