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

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

我希望是这样的:

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

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

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

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

578510 次浏览
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}


如果您使用的是iOS8或OS X Yosemite,现在可以执行以下操作:*注意:如果在iOS7设备上调用此代码,这将使您的应用程序崩溃)。

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

(这也是它在Swift中的工作方式)

对于iOS8.0+和macOS 10.10+,您可以使用NSString的原生#0

对于旧版本的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

注意:观察下面Daniel Galasko关于命名的评论

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

//您也可以使用以下选项:

if (rangeValue.location == NSNotFound){NSLog(@"string does not contain hello");}else{NSLog(@"string contains hello!");}

Oneliner(代码量较小。DRY,因为你只有一个NSLog):

NSString *string = @"hello bla bla";NSLog(@"String %@", ([string rangeOfString:@"bla"].location == NSNotFound) ? @"not found" : @"cotains bla");

P i的解的改进版本,NSString上的一个类别,它不仅会告诉,如果在另一个字符串中找到一个字符串,而且还通过引用获取一个范围,是:

@interface NSString (Contains)-(BOOL)containsString: (NSString*)substringatRange:(NSRange*)range;
-(BOOL)containsString:(NSString *)substring;@end
@implementation NSString (Contains)
-(BOOL)containsString:(NSString *)substringatRange:(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:substringatRange:NULL];}
@end

像这样使用它:

NSString *string = @"Hello, World!";
//If you only want to ensure a string contains a certain substringif ([string containsString:@"ello" atRange:NULL]) {NSLog(@"YES");}
// Or simplyif ([string containsString:@"ello"]) {NSLog(@"YES");}
//If you also want to know substring's rangeNSRange range;if ([string containsString:@"ello" atRange:&range]) {NSLog(@"%@", NSStringFromRange(range));}

这是一个复制粘贴函数片段:

-(BOOL)Contains:(NSString *)StrSearchTerm on:(NSString *)StrText{return [StrText rangeOfString:StrSearchTermoptions:NSCaseInsensitiveSearch].location != NSNotFound;}

由于这似乎是Google的高排名结果,我想补充一下:

iOS8和OS X 10.10将#0方法添加到NSString。Dave DeLong针对这些系统的示例的更新版本:

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

对于iOS8Swift,我们可以使用localizedCaseInsensitiveContainsString方法

 let string: NSString = "Café"let substring: NSString = "É"
string.localizedCaseInsensitiveContainsString(substring) // true

如果你需要这一次写:

NSString *stringToSearchThrough = @"-rangeOfString method finds and returns the range of the first occurrence of a given string within the receiver.";BOOL contains = [stringToSearchThrough rangeOfString:@"occurence of a given string"].location != NSNotFound;

如果不关心区分大小写的字符串。就这一次

NSString *string  = @"Hello World!";
if([string rangeOfString:@"hello" options:NSCaseInsensitiveSearch].location !=NSNotFound){NSLog(@"found");}else{NSLog(@"not found");}
NSString *categoryString = @"Holiday Event";if([categoryString rangeOfString:@"Holiday"].location == NSNotFound){//categoryString does not contains Holiday}else{//categoryString contains Holiday}

请使用此代码

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

所以就个人而言,我真的很讨厌NSNotFound,但理解它的必要性。

但是有些人可能不理解与NSNotFint进行比较的复杂性

例如,这段代码:

- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {if([string rangeOfString:otherString].location != NSNotFound)return YES;elsereturn NO;}

有其问题:

1)显然如果otherString = nil这个代码会崩溃。一个简单的测试是:

NSLog(@"does string contain string - %@", [self doesString:@"hey" containString:nil] ? @"YES": @"NO");

结果!!崩溃!!

2)对于刚接触Objective-c的人来说,不太明显的是,当string = nil时,相同的代码不会崩溃。例如,以下代码:

NSLog(@"does string contain string - %@", [self doesString:nil containString:@"hey"] ? @"YES": @"NO");

和这个代码:

NSLog(@"does string contain string - %@", [self doesString:nil containString:nil] ? @"YES": @"NO");

都将导致

does string contains string - YES

这显然不是你想要的。

所以我认为更好的解决方案是使用rangeOfString返回长度为0的事实,所以更好更可靠的代码是这样的:

- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {if(otherString && [string rangeOfString:otherString].length)return YES;elsereturn NO;}

或简单:

- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {return (otherString && [string rangeOfString:otherString].length);}

对于1号和2号案件

does string contains string - NO

那是我的2美分;-)

请查看我的要点以获取更多有用的代码。

试试这个,

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

在Swift的情况下,这可以用来

let string = "Package #23"if string.containsString("Package #") {//String contains substring}else {//String does not contain substring}

最佳解决方案。就这么简单!如果你想找到一个词或字符串的一部分。您可以使用此代码。在此示例中,我们将检查word的值是否包含“acter”。

NSString *word =@"find a word or character here";if ([word containsString:@"acter"]){NSLog(@"It contains acter");} else {NSLog (@"It does not contain acter");}

在Swift 4中:

let a = "Hello, how are you?"a.contains("Hello")   //will return true

第一个字符串包含或不包含第二个字符串,

NSString *first = @"Banana";NSString *second = @"BananaMilk";NSRange range = [first rangeOfString:second options:NSCaseInsensitiveSearch];
if (range.length > 0) {NSLog(@"Detected");}else {NSLog(@"Not detected");}

使用带有rangeOfString的选项NSCaseInSentiveSearch:选项:

NSString *me = @"toBe" ;NSString *target = @"abcdetobe" ;NSRange range = [target  rangeOfString: me options: NSCaseInsensitiveSearch];NSLog(@"found: %@", (range.location != NSNotFound) ? @"Yes" : @"No");if (range.location != NSNotFound) {// your code}

找到输出结果:是

这些选项可以一起“或”,包括:

NS不区分大小写搜索国家搜索算法搜索和更多

Swift 4及以上

let str = "Hello iam midhun"
if str.contains("iam") {//contains substring}else {//doesn't contain substring}

Objective-c

NSString *stringData = @"Hello iam midhun";
if ([stringData containsString:@"iam"]) {//contains substring}else {//doesn't contain substring}

试试这个:

Swift 4.1、4.2:

let stringData = "Black board"
//swift quick way and case sensitiveif stringData.contains("bla") {print("data contains string");}
//case sensitiveif stringData.range(of: "bla",options: .caseInsensitive) != nil {print("data contains string");}else {print("data does not contains string");}

对于Objective-C:

NSString *stringData = @"Black board";
//Quick way and case sensitiveif ([stringData containsString:@"bla"]) {NSLog(@"data contains string");}
//Case Insensitiveif ([stringData rangeOfString:@"bla" options:NSCaseInsensitiveSearch].location != NSNotFound) {NSLog(@"data contains string");}else {NSLog(@"data does not contain string");}