ios 如何在 Objective-C 中检查一个字符串是否包含另一个字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2753956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I check if a string contains another string in Objective-C?
提问by Jonathan.
How can I check if a string (NSString) contains another smaller string?
如何检查字符串 ( NSString) 是否包含另一个较小的字符串?
I was hoping for something like:
我希望是这样的:
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?
无论如何,这是查找字符串是否包含另一个字符串的最佳方法吗?
回答by Dave DeLong
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 NSRangestruct, and the documentation saysthat it returns the struct {NSNotFound, 0}if the "haystack" does not contain the "needle".
关键是注意rangeOfString:返回一个NSRange结构,文档说{NSNotFound, 0}如果“干草堆”不包含“针” ,它会返回结构。
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).
如果您使用的是 iOS 8 或 OS X Yosemite,您现在可以执行以下操作:(*注意:如果在 iOS7 设备上调用此代码,这将使您的应用程序崩溃)。
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)
(这也是它在 Swift 中的工作方式)
回答by P i
For iOS 8.0+ and macOS 10.10+, you can use NSString's native containsString:.
对于 iOS 8.0+ 和 macOS 10.10+,您可以使用 NSString 的原生containsString:.
For older versions of iOS and macOS, you can create your own (obsolete) category for NSString:
对于旧版本的 iOS 和 macOS,您可以为 NSString 创建您自己的(过时的)类别:
@interface NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring;
@end
// - - - -
@implementation NSString ( SubstringSearch )
- (BOOL)containsString:(NSString *)substring
{
NSRange range = [self rangeOfString : substring];
BOOL found = ( range.location != NSNotFound );
return found;
}
@end
Note: Observe Daniel Galasko's comment below regarding naming
注意:请注意以下 Daniel Galasko 关于命名的评论
回答by Lukas
Since this seems to be a high-ranking result in Google, I want to add this:
由于这似乎是 Google 中排名靠前的结果,因此我想添加以下内容:
iOS 8 and OS X 10.10 add the containsString:method to NSString. An updated version of Dave DeLong's example for those systems:
的iOS 8和OS X 10.10添加containsString:的方法NSString。这些系统的 Dave DeLong 示例的更新版本:
NSString *string = @"hello bla bla";
if ([string containsString:@"bla"]) {
NSLog(@"string contains bla!");
} else {
NSLog(@"string does not contain bla");
}
回答by AJS
NSString *myString = @"hello bla bla";
NSRange rangeValue = [myString rangeOfString:@"hello" options:NSCaseInsensitiveSearch];
if (rangeValue.length > 0)
{
NSLog(@"string contains hello");
}
else
{
NSLog(@"string does not contain hello!");
}
//You can alternatively use following too :
//您也可以使用以下方法:
if (rangeValue.location == NSNotFound)
{
NSLog(@"string does not contain hello");
}
else
{
NSLog(@"string contains hello!");
}
回答by Govind
With iOS 8and Swift, we can use localizedCaseInsensitiveContainsStringmethod
在iOS 8和Swift 中,我们可以使用localizedCaseInsensitiveContainsStringmethod
let string: NSString = "Café"
let substring: NSString = "é"
string.localizedCaseInsensitiveContainsString(substring) // true
回答by ucangetit
So personally I really hate NSNotFoundbut understand its necessity.
所以我个人真的很讨厌NSNotFound但理解它的必要性。
But some people may not understand the complexities of comparing against NSNotFound
但是有些人可能不明白对比 NSNotFound 的复杂性
For example, this code:
例如,这段代码:
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
if([string rangeOfString:otherString].location != NSNotFound)
return YES;
else
return NO;
}
has its problems:
有它的问题:
1) Obviously if otherString = nilthis code will crash. a simple test would be:
1)显然,如果otherString = nil此代码会崩溃。一个简单的测试是:
NSLog(@"does string contain string - %@", [self doesString:@"hey" containString:nil] ? @"YES": @"NO");
results in !! CRASH !!
结果是 !!碰撞 !!
2) What is not so obvious to someone new to objective-c is that the same code will NOT crash when string = nil.
For example, this code:
2) 对于 Objective-c 的新手来说,不太明显的是,相同的代码在string = nil. 例如,这段代码:
NSLog(@"does string contain string - %@", [self doesString:nil containString:@"hey"] ? @"YES": @"NO");
and this code:
和这个代码:
NSLog(@"does string contain string - %@", [self doesString:nil containString:nil] ? @"YES": @"NO");
will both result in
两者都会导致
does string contains string - YES
Which is clearly NOT what you want.
这显然不是你想要的。
So the better solution that I believe works is to use the fact that rangeOfString returns the length of 0 so then a better more reliable code is this:
所以我认为更好的解决方案是使用 rangeOfString 返回长度为 0 的事实,所以更好更可靠的代码是这样的:
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
if(otherString && [string rangeOfString:otherString].length)
return YES;
else
return NO;
}
OR SIMPLY:
或者简单地:
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
return (otherString && [string rangeOfString:otherString].length);
}
which will for cases 1 and 2 will return
对于情况 1 和 2 将返回
does string contains string - NO
That's my 2 cents ;-)
那是我的 2 美分 ;-)
Please check out my Gistfor more helpful code.
请查看我的Gist以获得更多有用的代码。
回答by vikingosegundo
An improved version of P i's solution, a category on NSString, that not only will tell, if a string is found within another string, but also takes a range by reference, is:
P i的解决方案的改进版本,NSString 上的一个类别,它不仅会告诉,是否在另一个字符串中找到一个字符串,而且还会通过引用获取一个范围,是:
@interface NSString (Contains)
-(BOOL)containsString: (NSString*)substring
atRange:(NSRange*)range;
-(BOOL)containsString:(NSString *)substring;
@end
@implementation NSString (Contains)
-(BOOL)containsString:(NSString *)substring
atRange:(NSRange *)range{
NSRange r = [self rangeOfString : substring];
BOOL found = ( r.location != NSNotFound );
if (range != NULL) *range = r;
return found;
}
-(BOOL)containsString:(NSString *)substring
{
return [self containsString:substring
atRange:NULL];
}
@end
Use it like:
像这样使用它:
NSString *string = @"Hello, World!";
//If you only want to ensure a string contains a certain substring
if ([string containsString:@"ello" atRange:NULL]) {
NSLog(@"YES");
}
// Or simply
if ([string containsString:@"ello"]) {
NSLog(@"YES");
}
//If you also want to know substring's range
NSRange range;
if ([string containsString:@"ello" atRange:&range]) {
NSLog(@"%@", NSStringFromRange(range));
}
回答by Durai Amuthan.H
Here is a copy-and-paste function snippet:
这是一个复制和粘贴功能片段:
-(BOOL)Contains:(NSString *)StrSearchTerm on:(NSString *)StrText
{
return [StrText rangeOfString:StrSearchTerm
options:NSCaseInsensitiveSearch].location != NSNotFound;
}
回答by Ada
NSString *categoryString = @"Holiday Event";
if([categoryString rangeOfString:@"Holiday"].location == NSNotFound)
{
//categoryString does not contains Holiday
}
else
{
//categoryString contains Holiday
}
回答by jerik
Oneliner (Smaller amount of code. DRY, as you have only one NSLog):
Oneliner(代码量较少。DRY,因为你只有一个NSLog):
NSString *string = @"hello bla bla";
NSLog(@"String %@", ([string rangeOfString:@"bla"].location == NSNotFound) ? @"not found" : @"cotains bla");

