How do I check if a string contains another string

2018-12-31 16:49发布

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

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?

21条回答
伤终究还是伤i
2楼-- · 2018-12-31 17:43
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!");
}
查看更多
孤独寂梦人
3楼-- · 2018-12-31 17:43

If certain position of the string is needed, this code comes to place in Swift 3.0:

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

let position = string.range(of: substring)?.lowerBound
查看更多
宁负流年不负卿
4楼-- · 2018-12-31 17:45

In Swift 4:

let a = "Hello, how are you?"
a.contains("Hello")   //will return true
查看更多
登录 后发表回答