简体   繁体   中英

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?

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

Try this one

NSArray *qwer=[NSArray arrayWithObjects:@"Apple Juice",@"Apple cake",@"Apple chips",@"Apple wassail",nil];
for(int k=0; k<qwer.count; k++) {
    NSString *currentString =[qwer objectAtIndex:k];
    if ([currentString rangeOfString:@"wassail"].location == NSNotFound) {
        NSLog(@"string does not contain wassail");
    } else {
        NSLog(@"string contains wassail!");

        break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM