trimmingCharacters在iOS 10.3 Xcode8.3上不起作用

lee*_*lee -8 string ios swift xcode8 ios10.3

请帮帮我,我使用Xcode 8.3(swift 3.1),功能trimmingCharacters不起作用.我的代码如下:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if var searchStr = textField.text{
       let _searchStr = searchStr.trimmingCharacters(in: .whitespaces)
       print("After trimming:\(_searchStr)")
   }
}
Run Code Online (Sandbox Code Playgroud)

文本字段中的输入是409 hu?nh,打印结果409 hu?nh 不符合预期:409huỳnh.

vad*_*ian 7

从文档:

通过接收器的两端移除 set中包含的字符而生成的新字符串.

它并没有在字符串中的字符删除.

您可以.whitespaces使用正则表达式替换字符串中的空格(对应于字符集):

let _searchStr = searchStr.replacingOccurrences(of: "\\s", with: "", options: .regularExpression)
Run Code Online (Sandbox Code Playgroud)


Leo*_*bus 5

您可以使用 Swift 5 Character 属性isWhitespace并过滤字符串中的所有非空格:

let string = "409 hu?nh"
let result = string.filter { !$0.isWhitespace }
print(result)  // "409hu?nh"
Run Code Online (Sandbox Code Playgroud)