在 swift 中用字符串中的其他字符替换多个字符的更简单方法是什么?

What is an easier way to replace multiple characters with other characters in a string in swift?

我目前正在尝试设置要添加到 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)

最好使用 .urlHostAllowed CharacterSet,因为它几乎总是有效。

textInput.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

但最好的办法是结合所有可能的选项,例如 ,这将确保您做对了。

我认为使用 addingPercentEncoding 运行 的唯一问题是您的问题指出 space " " 应该替换为下划线。对 space " " 使用 addingPercentEncoding 将 return %20。您应该能够组合其中的一些答案,定义列表中应该 return 标准字符替换的剩余字符,并获得您想要的结果。

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