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

标签 swift character-replacement

我目前正在尝试设置一个字符串以添加到 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/

相关文章:

ios - 如何传递 UnsafeMutablePointer<UnsafePointer<Void>> 类型的参数

c++ - 如何用常量字符替换字符串的子字符串,如 'X'

替换字符的 Pythonic 方式

ruby - 我可以使用 Swift 的 Ruby 正则表达式引擎吗?

ios - TabBarController 顶部栏

json - Firebase 数据库搜索查询

bash - 将 FASTA 文件中的数值替换为不同文件中的索引。 (首选 Bash)

Powershell,用空格替换 DOT

java - java中如何删除字符串中的中间字符?

ios - Xcode 错误 : Outlets cannot be connected to repeating content