且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查字符串是否包含Objective-C中的另一个字符串?

更新时间:2022-11-17 13:52:52

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

关键是注意 rangeOfString:返回 NSRange 结构,文档说它返回结构 {NSNotFound,0 } 如果haystack不包含needle。

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".

如果你在iOS 8或OS X Yosemite上,您现在可以:(*注意:如果在iOS7设备上调用此代码,这将使您的应用程序崩溃)。

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");
}