Search code examples
iosobjective-cnsarray

Checking whether elements of an Array contains a specified String


I am working on an iOS app. I have an array,

NSArray *qwer=[NSArray arrayWithObjects:@"Apple Juice",@"Apple cake",@"Apple chips",@"Apple wassail"nil];
for(int k=0; k<qwer.count; k++) {
    //
}

I am trying to check whether my array contains string 'wassail'. Can anyone help me to find this?


Solution

  • NSString has a rangeOfString function that can be used for looking up partial string matches. This function returns NSRange. You can use the location property.

    ...
      NSArray *qwer = [NSArray arrayWithObjects:@"Apple Juice",@"Apple cake",@"Apple chips",@"Apple wassail"nil];
        for (NSString *name in qwer){
          if ([name rangeOfString:keyword].location == NSNotFound) {
            NSLog(@"contains");
          } 
        }
    ...
    

    Reference :

    1. https://developer.apple.com/reference/foundation/nsstring/1416849-rangeofstring
    2. https://developer.apple.com/reference/foundation/nsrange

    Thanks Sriram