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


1212

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

我希望有这样的东西:

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

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

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

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


1
我也希望添加它,但是与此同时,将其添加为NSString上的类别相对容易。
isaac

2
使用时if ([string rangeOfString:@"hello"] == 0) {...},NSRange和int存在类型不匹配错误。要解决此问题,您应该将行更改为以下内容:if ([string rangeOfString:@"hello"].length == 0) {...}
Neeku 2013年

1
iOS 8添加了containsString:这是添加iOS 7支持的一种微创方法petersteinberger.com/blog/2014/…–
Steve Moser

2
从一开始我就一直是iOS开发人员,并且我会不断地回顾这篇文章以进行快速复制粘贴。我似乎无法记住这一点。我历史上访问量最大的stackoverflow帖子。
VaporwareWolf's

只需使用Swift;)
Fattie

Answers:


2436
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}如果“干草堆”中不包含“ needle” ,它将返回该结构。


而且,如果您使用的是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");
}

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

👍


286
要进行不区分大小写的搜索,请使用“ if([[string rangeOfString:@“ bla”选项:NSCaseInsensitiveSearch] .location!= NSNotFound)”
Vanja

1
@Dave DeLong我只想提及我为此目的创建的类别,然后再阅读您对答案的编辑!因为我主要是ac#开发人员,所以我很高兴他们为NSSTring添加了一个contains方法。
dherrin79

如果我的部署目标是iOS7并且我使用containsString,为什么编译器什么也不说?
里卡多

3
为了进一步说明@Vanja的观点,如果要使用iOS 8 / Yosemite中引入的[string containsString]快捷方式代码,则可以对不区分大小写的字符串使用以下代码:“ [stringToSearch localizedCaseInsensitiveContainsString:string ]”,如果要进行大小写和变音符号不敏感的搜索,则使用以下命令:“ [stringToSearch localizedStandardContainsString:string]”。
Scott Kohlert

1
请注意,当string为!时,表达式[string rangeOfString:@"bla"].location != NSNotFound将为truenil
funroll

158

对于iOS 8.0+和macOS 10.10+,您可以使用NSString的native containsString:

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


13
+1可获得更清晰的代码和可重用性。我将其转换为一个衬板,return [self rangeOfString:substring].location != NSNotFound;并将其包含在我的重构库es_ios_utils中。github.com/peterdeweese/es_ios_utils
Peter

4
看起来苹果喜欢您的想法,并在iOS 8和OSx 10.10(Yosemite)中添加了此功能,就像@DaveDeLong在他的回答中提到的那样。+1
Islam Q.

7
obj-c类别的基本规则是在方法名称前加上3个字母的模块前缀。这是一个完美的例子,因为它现在与iOS 7和10.10版本冲突
Daniel Galasko 2015年

54

由于这似乎是Google的高排名结果,因此我想添加以下内容:

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

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

22

iOS 8Swift中,我们可以使用localizedCaseInsensitiveContainsString 方法

 let string: NSString = "Café"
 let substring: NSString = "É"

 string.localizedCaseInsensitiveContainsString(substring) // true

1
很好 不知道为什么他们没有针对ios 7的这种方法
Lucas

@Lucas,因为Swift是在iOS 8.0上启动的。但随着SWIFT你仍然可以与iOS 7支持的设备
Hemang

13

所以我个人非常讨厌 NSNotFound但了解其必要性。

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

例如,此代码:

- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
    if([string rangeOfString:otherString].location != NSNotFound)
        return YES;
    else
        return 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;
    else
        return NO;
}

或简单地:

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

对于情况1和2将返回

does string contains string - NO

那是我的2美分;-)

请查看我的Gist以获得更多有用的代码。


12

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

像这样使用它:

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

8

这是一个复制粘贴功能代码段:

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

我可以知道为什么我被否决了吗?这是一个工作代码段
Durai Amuthan.H 2015年

6

Oneliner(少量的代码。DRY,因为您只有一个NSLog):

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

6
NSString *categoryString = @"Holiday Event";
if([categoryString rangeOfString:@"Holiday"].location == NSNotFound)
{
    //categoryString does not contains Holiday
}
else
{
    //categoryString contains Holiday
}

5

尝试这个,

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

5

最佳解决方案。就这么简单!如果要查找单词或字符串的一部分。您可以使用此代码。在此示例中,我们将检查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");
}

5

在Swift 4中:

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

4

如果需要一次,请写:

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;

4

万一迅速,可以使用

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

2

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

NSString *string  = @"Hello World!";

if([string rangeOfString:@"hello" options:NSCaseInsensitiveSearch].location !=NSNotFound)
{
    NSLog(@"found");
}
else
{
    NSLog(@"not found");
}

1

请使用此代码

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

1

将选项NSCaseInsensitiveSearch与rangeOfString:options一起使用:

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
}

找到输出结果:是

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

NSCaseInsensitiveSearch NSLiteralSearch NSBackwardsSearch等


0

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

NSString *first = @"Banana";
NSString *second = @"BananaMilk";
NSRange range = [first rangeOfString:second options:NSCaseInsensitiveSearch];

if (range.length > 0) {
    NSLog(@"Detected");
}
else {
    NSLog(@"Not detected");
}

0

尝试这个:

Swift 4.1、4.2:

let stringData = "Black board"

//swift quick way and case sensitive
if stringData.contains("bla") {
    print("data contains string");
}

//case sensitive
if 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 sensitive
if ([stringData containsString:@"bla"]) {
    NSLog(@"data contains string");
}

//Case Insensitive
if ([stringData rangeOfString:@"bla" options:NSCaseInsensitiveSearch].location != NSNotFound) {
   NSLog(@"data contains string");
}else {
   NSLog(@"data does not contain string");
}

0

斯威夫特4及以上

let str = "Hello iam midhun"

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

目标C

NSString *stringData = @"Hello iam midhun";

if ([stringData containsString:@"iam"]) {
    //contains substring
}
else {
    //doesn't contain substring
}

-1
-(Bool)checkIf:(String)parentString containsSubstring:(String)checkString {
    NSRange textRange =[parentString rangeOfString:checkString];
    return textRange.location != NSNotFound // returns true if parent string contains substring else returns false
  }

1
在Objective-C中,我们具有“ NSString”类型。我们没有String类型。其次,我们拥有所有对象。因此,您应该通过辩论NSString。由于在高度活跃的问题下回答的质量较差,我投票赞成删除。
Aleksey Potapov

-2

如果需要字符串的特定位置,则此代码将放置在Swift 3.0中

let string = "This is my string"
let substring = "my"

let position = string.range(of: substring)?.lowerBound
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.