2

I have an array and I want to check if one string is in the array, without looping. Just using "if's" I know if some string exists or not in the array.

Is there any possibility?

4
  • Maybe you could put the entire array into a hashmap and just check to see if the element is in the map. Commented May 26, 2012 at 5:25
  • Actually, @AdamMiller, I'm trying to let it really simple, so if I use hashmap's, I can use "for" loops. Equally, thanks for the help. :-) Commented May 26, 2012 at 5:28
  • let it really simple... ? Also, the answer is no, you can't do that without random access for a given key, which would be the string you want to check for. Arrays don't look up an item with a given key, they take an index to offset. Commented May 26, 2012 at 5:33
  • Thanks for the help, @AdamMiller. I'll try to change my code and find another way. Commented May 26, 2012 at 5:36

3 Answers 3

11

Use -[NSArray containsObject:].

(You don't have to write the loop yourself, but of course NSArray almost certainly has to use a loop internally.)

if ([array containsObject:string])
    NSLog(@"Yes, the array contains my string.")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, Kurt. I choose your question for the documentation link. ;-)
0

What about

if ([yourArray containsObject:@"string"]) {

}

??

Comments

0
NSarray *theArray; // assume exists
if ( [theArray containsObject:someString] )
{
    ...
}

Comments

Your Answer

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