How do I check if a string contains another string in Objective-C?

前端 未结 23 2021

How can I check if a string (NSString) contains another smaller string?

I was hoping for something like:

NSString *string = @\"hello bla         


        
23条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 15:00

    NSString *string = @"hello bla bla";
    if ([string rangeOfString:@"bla"].location == NSNotFound) {
      NSLog(@"string does not contain bla");
    } else {
      NSLog(@"string contains bla!");
    }
    

    The key is noticing that rangeOfString: returns an NSRange struct, and the documentation says that it returns the struct {NSNotFound, 0} if the "haystack" does not contain the "needle".


    And if you're on iOS 8 or OS X Yosemite, you can now do: (*NOTE: This WILL crash your app if this code is called on an iOS7 device).

    NSString *string = @"hello bla blah";
    if ([string containsString:@"bla"]) {
      NSLog(@"string contains bla!");
    } else {
      NSLog(@"string does not contain bla");
    }
    

    (This is also how it would work in Swift)

提交回复
热议问题