在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中做到这一点呢?
当前回答
另一个。支持大小写和变音符。
斯威夫特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 4方法检查子字符串,包括必要的基础(或UIKit)框架导入:
import Foundation // or UIKit
let str = "Oh Canada!"
str.contains("Can") // returns true
str.contains("can") // returns false
str.lowercased().contains("can") // case-insensitive, returns true
除非Foundation(或UIKit)框架被导入,str.contains("Can")将给出一个编译器错误。
这个答案是在重复manojlds的答案,而manojlds的答案是完全正确的。我不知道为什么这么多答案要经历这么多麻烦来重建Foundation's String。contains(subString:字符串)方法。
SWIFT 4非常简单!!
if (yourString.contains("anyThing")) {
print("Exist")
}
在iOS 8和更新版本中,你可以使用这两个NSString方法:
@availability(iOS, introduced=8.0)
func containsString(aString: String) -> Bool
@availability(iOS, introduced=8.0)
func localizedCaseInsensitiveContainsString(aString: String) -> Bool
您不需要为此编写任何定制代码。从1.2版本开始,Swift已经有了所有你需要的方法:
获取字符串长度:count(string); 检查字符串是否包含子字符串:contains(字符串,子字符串); 检查字符串是否以substring开头:startsWith(string, substring) 等。
在Swift 3中
if((a.range(of: b!, options: String.CompareOptions.caseInsensitive, range: nil, locale: nil)) != nil){
print("Done")
}