在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中做到这一点呢?
当前回答
Swift 5,不区分大小写:
如果string.localizedLowercase.contains(“迅速”.localizedLowercase) {
其他回答
>在swift 3.0
let str = "Hello Swift"
if str.lowercased().contains("Swift".lowercased()) {
print("String Contains Another String")
} else {
print("Not Exists")
}
输出
String Contains Another String
有了swift 4的新语法,你就可以
字符串。包含(“Swift 4是最好的”)
String是你的字符串变量
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:字符串)方法。
在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) 等。