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

How do I check if a string contains another string in Objective-C?

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

我希望有这样的事情:

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

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

1
2
3
4
5
6
if ([string rangeOfString:@"hello"] == 0) {
    NSLog(@"sub string doesnt exist");
}
else {
    NSLog(@"exists");
}

不管怎样,这是查找一个字符串是否包含另一个字符串的最佳方法吗?


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

关键是注意到rangeOfString:返回一个NSRange结构,并且文档说如果"haystack"不包含"针",它将返回结构{NSNotFound, 0}

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

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

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

??


注意:这个答案现在已经过时了

为nsstring创建类别:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@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

编辑:观察丹尼尔·加拉斯科关于命名的评论


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

iOS 8和OS X 10.10将containsString:方法添加到NSString中。戴夫·德龙的这些系统示例的更新版本:

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

1
2
3
4
5
6
7
8
9
10
11
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!");
}

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

1
2
3
4
5
6
7
8
if (rangeValue.location == NSNotFound)
{
    NSLog(@"string does not contain hello");
}
else
{
    NSLog(@"string contains hello!");
}


使用iOS 8和swift,我们可以使用localizedCaseInsensitiveContainsString方法

1
2
3
4
 let string: NSString ="Café"
 let substring: NSString ="é"

 string.localizedCaseInsensitiveContainsString(substring) // true


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

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

例如,此代码:

1
2
3
4
5
6
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
    if([string rangeOfString:otherString].location != NSNotFound)
        return YES;
    else
        return NO;
}

有问题:

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

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

结果!崩溃!!

2)对于不熟悉Objective-C的人来说,不太明显的是,当string = nil时,相同的代码不会崩溃。例如,此代码:

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

这个代码:

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

都会导致

1
does string contains string - YES

这显然不是你想要的。

因此,我认为更好的解决方案是使用RangeOfString返回0的长度这一事实,因此更可靠的代码是:

1
2
3
4
5
6
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
    if(otherString && [string rangeOfString:otherString].length)
        return YES;
    else
        return NO;
}

或者简单地说:

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

第1和第2种情况将返回

1
does string contains string - NO

那是我的2美分;-)

请查看我的要点了解更多有用的代码。


P I解决方案的一个改进版本,NSstring上的一个类别,它不仅可以说明在另一个字符串中是否找到了一个字符串,而且还可以通过引用获得一个范围,它是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@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

像这样使用它:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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));
}

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

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


1
2
3
4
5
6
7
8
9
NSString *categoryString = @"Holiday Event";
if([categoryString rangeOfString:@"Holiday"].location == NSNotFound)
{
    //categoryString does not contains Holiday
}
else
{
    //categoryString contains Holiday
}


一行程序(代码量较小。干燥,因为您只有一个NSLog

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

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

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

试试这个,

1
2
3
4
5
6
7
8
9
NSString *string = @"test Data";
if ([[string lowercaseString] rangeOfString:@"data"].location == NSNotFound)
{
    NSLog(@"string does not contain Data");
}  
else
{
    NSLog(@"string contains data!");
}

在SWIFT 4中:

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

如果是Swift,可以使用

1
2
3
4
5
6
7
let string ="Package #23"
if string.containsString("Package #") {
    //String contains substring
}
else {
    //String does not contain substring
}


如果您需要,请写下:

1
2
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;

如果不关心区分大小写的字符串。试试这个。

1
2
3
4
5
6
7
8
9
10
NSString *string  = @"Hello World!";

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

使用选项nscaseinsensitivesearch和rangeofstring:选项:

1
2
3
4
5
6
7
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
}

找到输出结果:是

这些选项可以一起"或"编辑,包括:

NScase不敏感搜索NSL搜索nsbackwardssearch等


请用这个代码

1
2
3
4
5
6
7
8
9
NSString *string = @"hello bla bla";
if ([string rangeOfString:@"bla"].location == NSNotFound)
{
    NSLog(@"string does not contain bla");
}
else
{  
    NSLog(@"string contains bla!");
}

试试这个:

SWIFT 4.1、4.2:

1
2
3
4
5
6
7
8
9
10
11
12
13
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");
}

目标C:

1
2
3
4
5
6
7
8
9
10
11
12
13
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");
}


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

1
2
3
4
5
6
7
8
9
10
NSString *first = @"Banana";
NSString *second = @"BananaMilk";
NSRange range = [first rangeOfString:second options:NSCaseInsensitiveSearch];

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

Swift 4及以上

1
2
3
4
5
6
7
8
 let str ="Hello iam midhun"

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

如果需要字符串的某个位置,则此代码将放在swift 3.0中:

1
2
3
4
let string ="This is my string"
let substring ="my"

let position = string.range(of: substring)?.lowerBound