我目前正在尝试设置一个字符串以添加到 HTTP POST 请求中,用户可以在其中键入文本并点击“enter”并发送请求。
我知道多个字符 (^,+,<,>) 可以替换为单个字符 ('_'),如下所示:
userText.replacingOccurrences(of: "[^+<>]", with: "_"
我目前正在使用以下的多项功能:
.replacingOccurrences(of: StringProtocol, with:StringProtocol)
像这样:
let addAddress = userText.replacingOccurrences(of: " ", with: "_").replacingOccurrences(of: ".", with: "%2E").replacingOccurrences(of: "-", with: "%2D").replacingOccurrences(of: "(", with: "%28").replacingOccurrences(of: ")", with: "%29").replacingOccurrences(of: ",", with: "%2C").replacingOccurrences(of: "&", with: "%26")
有没有更有效的方法?
最佳答案
您正在做的是使用百分比编码手动对字符串进行编码。
如果是这样,这将帮助您:
addingPercentEncoding(withAllowedCharacters:)
Returns a new string made from the receiver by replacing all characters not in the specified set with percent-encoded characters.
https://developer.apple.com/documentation/foundation/nsstring/1411946-addingpercentencoding
对于您的具体情况,这应该有效:
userText.addingPercentEncoding(withAllowedCharacters: .alphanumerics)
关于swift - 在 swift 中用字符串中的其他字符替换多个字符的更简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49058697/