如何检查字符串是否包含Objective-C中的另一个字符串? [英] How do I check if a string contains another string in Objective-C?

查看:138
本文介绍了如何检查字符串是否包含Objective-C中的另一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查字符串( NSString )是否包含另一个较小的字符串?

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

我希望类似于:

NSString *string = @"hello bla bla";
NSLog(@"%d",[string containsSubstring:@"hello"]);

但我能找到的最接近的是:

But the closest I could find was:

if ([string rangeOfString:@"hello"] == 0) {
    NSLog(@"sub string doesnt exist");
} 
else {
    NSLog(@"exists");
}

无论如何,这是查找字符串是否包含其他字符串的最佳方法吗?

Anyway, is that the best way to find if a string contains another string?

推荐答案

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

这篇关于如何检查字符串是否包含Objective-C中的另一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆