检查 String 是否包含定义集中的字符
快报
Version = 3.0
let letters = CharacterSet.letters
let phrase = "Test case"
let range = phrase.rangeOfCharacter(from: letters)
// range will be nil if no letters is found
if let test = range {
print("letters found")
}
else {
print("letters not found")
}
Version = 2.2
let letters = NSCharacterSet.letterCharacterSet()
let phrase = "Test case"
let range = phrase.rangeOfCharacterFromSet(letters)
// range will be nil if no letters is found
if let test = range {
print("letters found")
}
else {
print("letters not found")
}
同时桥接到 Objective-C NSCharacterSet
类的新 CharacterSet
结构定义了几个预定义集:
decimalDigits
capitalizedLetters
alphanumerics
controlCharacters
illegalCharacters
- 你可以在 NSCharacterSet 参考中找到更多内容。
你还可以定义自己的字符集:
Version = 3.0
let phrase = "Test case"
let charset = CharacterSet(charactersIn: "t")
if let _ = phrase.rangeOfCharacter(from: charset, options: .caseInsensitive) {
print("yes")
}
else {
print("no")
}
Version = 2.2
let charset = NSCharacterSet(charactersInString: "t")
if let _ = phrase.rangeOfCharacterFromSet(charset, options: .CaseInsensitiveSearch, range: nil) {
print("yes")
}
else {
print("no")
}
你还可以包括范围:
Version = 3.0
let phrase = "Test case"
let charset = CharacterSet(charactersIn: "t")
if let _ = phrase.rangeOfCharacter(from: charset, options: .caseInsensitive, range: phrase.startIndex..<phrase.endIndex)) {
print("yes")
}
else {
print("no")
}