我正在尝试修剪电话号码并使用以下代码,但它不会修剪空格或“ - ”。我需要擦除所有字符,除了字符集中的字符
func trimmedNumber(s : String)->String
{
let characterSet = NSCharacterSet(charactersInString: "+*#0123456789")
let trimmedString = s.stringByTrimmingCharactersInSet(characterSet.invertedSet)
return trimmedString
}
答案 0 :(得分:20)
Swift 3/4:
let set = CharacterSet(charactersIn: "+*#0123456789")
let stripped = s.components(separatedBy: set.inverted).joined()
答案 1 :(得分:7)
func trimmedNumber(s : String) -> String {
let characterSet = Set("+*#0123456789".characters)
return String(s.characters.lazy.filter(characterSet.contains))
}
或者在Swift 1中:
func trimmedNumber(s : String) -> String {
let characterSet = Set("+*#0123456789")
return String(lazy(s).filter { characterSet.contains($0) })
}
答案 2 :(得分:3)
适用于swift 1& 2
let s = "adasdad+3124124+r323*4asdasdbk*($&#@"
let characterSet = NSCharacterSet(charactersInString: "+*#0123456789").invertedSet;
let elements = s.componentsSeparatedByCharactersInSet(characterSet)
let filtered = (elements as NSArray).componentsJoinedByString("")
print(filtered);
答案 3 :(得分:2)
将方法removingCharacters(in:)
添加到Swift的String
类型。它返回一个新字符串,该字符串是通过从String
中删除给定字符集中的字符而生成的。
例如:
let string = "+1-202-555-0141"
let set = CharacterSet(charactersIn: "+*#0123456789")
let sanitized = string.removingCharacters(in: set.inverted)
// sanitized is equal to "+12025550141"
Helpers.swift
extension String {
public func removingCharacters(in set: CharacterSet) -> String {
let filtered = unicodeScalars.lazy.filter { !set.contains($0) }
return String(String.UnicodeScalarView(filtered))
}
}
HelpersTests.swift
import XCTest
class HelpersTests: XCTestCase {
func testRemovingCharacters() {
let inputText1 = ""
let set1 = CharacterSet.decimalDigits.inverted
let sanitized1 = inputText1.removingCharacters(in: set1)
XCTAssertEqual("", sanitized1)
let inputText2 = " tab:\tspace: no-break_space: "
let set2 = CharacterSet.whitespaces
let sanitized2 = inputText2.removingCharacters(in: set2)
XCTAssertEqual("tab:space:no-break_space:", sanitized2)
let inputText3 = " aBc!@#12 $%^&*()-_=+[{]}\\|;:'\"3,<.>/?`~ "
let set3 = CharacterSet.alphanumerics.inverted
let sanitized3 = inputText3.removingCharacters(in: set3)
XCTAssertEqual("aBc123", sanitized3)
}
}