更新:Xcode 7.2 • Swift 2.1.1
extension String {
var numbersOnly: String {
return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "1234567890")
.invertedSet)
.joinWithSeparator("")
}
var numbersExempt: String {
return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "1234567890"))
.joinWithSeparator("")
}
var charactersOnly: String {
return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").invertedSet).joinWithSeparator("")
}
var charactersExempt: String {
return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")).joinWithSeparator("")
}
func keep(keepIt: String) -> String {
return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: keepIt).invertedSet).joinWithSeparator("")
}
func exclude(excludeIt: String) -> String {
return componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: excludeIt)).joinWithSeparator("")
}
}
let phoneNumber = "+1 (555) 555 - 5555".numbersOnly
print(phoneNumber) // "15555555555"
let excludePlusMinus = "+1 (555) 555-5555".exclude("+-") // "1 (555) 5555555"
let keepWhatever = "+1 (555) 555-5555".keep("()-+") // "+()-"
您还可以使用您的函数通过一些调整仅减去空格。试试这样:
func sostituisci(stringa: String) -> String {
return stringa.stringByReplacingOccurrencesOfString(" ", withString: "")
}
sostituisci("1 234 567 8901") // "12345678901"
或者像一个扩展:
extension String {
var sostituisci: String {
return stringByReplacingOccurrencesOfString(" ", withString: "")
}
}
let phoneNumber2 = "1 234 567 8901".sostituisci