我如何检查一个字符串(NSString)包含另一个较小的字符串?
我希望是这样的:
NSString *string = @"hello bla bla";
NSLog(@"%d",[string containsSubstring:@"hello"]);
但我能找到的最接近的是:
if ([string rangeOfString:@"hello"] == 0) {
NSLog(@"sub string doesnt exist");
}
else {
NSLog(@"exists");
}
不管怎样,这是找出字符串是否包含另一个字符串的最好方法吗?
试试这个:
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");
}