檢查 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")
}