我目前正在尝试设置一个字符串,以添加到HTTP POST请求中,用户可以在其中键入文本并点击“输入”,然后发送请求。
我知道多个字符(^,+,<,>)可以替换为单个字符('_'),如下所示:
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")
有更有效的方法吗?
我认为使用addsPercentEncoding会遇到的唯一问题是你的问题表明空格“”应该用下划线替换。对空格“”使用addsPercentEncoding将返回%20。您应该能够将这些答案中的一些结合起来,定义列表中应该返回标准字符替换的剩余字符,并获得所需的结果。
var userText = "This has.lots-of(symbols),&stuff"
userText = userText.replacingOccurrences(of: " ", with: "_")
let allowedCharacterSet = (CharacterSet(charactersIn: ".-(),&").inverted)
var newText = userText.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)
print(newText!) // Returns This_has%2Elots%2Dof%28symbols%29%2C%26stuff
你要做的是用百分比编码手动编码字符串。
如果是这种情况,这将有助于您:
addingPercentEncoding(withAllowedCharacters:)
通过将所有不在指定集中的字符替换为百分比编码字符,返回从接收方生成的新字符串。
https://developer.apple.com/documentation/foundation/nsstring/1411946-addingpercentencoding
对于您的具体情况,这应该工作:
userText.addingPercentEncoding(withAllowedCharacters: .alphanumerics)
理想情况下使用.urlHostAllowed
CharacterSet,因为它几乎总能使用。
textInput.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
但最好的是结合所有可能的选项,如here,这将确保你做对。