在Objective-C中,检查NSString子字符串的代码是:
NSString *string = @"hello Swift";
NSRange textRange =[string rangeOfString:@"Swift"];
if(textRange.location != NSNotFound)
{
NSLog(@"exists");
}
但是如何在Swift中做到这一点呢?
在Objective-C中,检查NSString子字符串的代码是:
NSString *string = @"hello Swift";
NSRange textRange =[string rangeOfString:@"Swift"];
if(textRange.location != NSNotFound)
{
NSLog(@"exists");
}
但是如何在Swift中做到这一点呢?
当前回答
给你:
let s = "hello Swift"
if let textRange = s.rangeOfString("Swift") {
NSLog("exists")
}
其他回答
另一个。支持大小写和变音符。
斯威夫特3.0
struct MyString {
static func contains(_ text: String, substring: String,
ignoreCase: Bool = true,
ignoreDiacritic: Bool = true) -> Bool {
var options = NSString.CompareOptions()
if ignoreCase { _ = options.insert(NSString.CompareOptions.caseInsensitive) }
if ignoreDiacritic { _ = options.insert(NSString.CompareOptions.diacriticInsensitive) }
return text.range(of: substring, options: options) != nil
}
}
使用
MyString.contains("Niels Bohr", substring: "Bohr") // true
iOS 9 +
iOS 9开始提供大小写和变音符不敏感功能。
if #available(iOS 9.0, *) {
"Für Elise".localizedStandardContains("fur") // true
}
在Swift 3中
if((a.range(of: b!, options: String.CompareOptions.caseInsensitive, range: nil, locale: nil)) != nil){
print("Done")
}
您不需要为此编写任何定制代码。从1.2版本开始,Swift已经有了所有你需要的方法:
获取字符串长度:count(string); 检查字符串是否包含子字符串:contains(字符串,子字符串); 检查字符串是否以substring开头:startsWith(string, substring) 等。
如果你想检查一个字符串中是否包含另一个子字符串,你也可以这样检查,
var name = String()
name = "John has two apples."
现在,在这个特定的字符串中,如果你想知道它是否包含名为apple的水果,你可以这样做,
if name.contains("apple") {
print("Yes , it contains fruit name")
} else {
print("it does not contain any fruit name")
}
希望这对你有用。
SWIFT 4非常简单!!
if (yourString.contains("anyThing")) {
print("Exist")
}