【问题标题】:String decoding help needed需要字符串解码帮助
【发布时间】:2018-05-27 19:37:16
【问题描述】:

我正在从 API 获得这种类型的编码字符串作为响应。我不知道使用了什么编码以及如何解码。需要跨 ios 和 android 对其进行编码。

  1.5%23%23cups%23%23BISQUICK*+mix%23%23%0A0.333%23%23cup%23%23hot+water%23%23%0A3%23%23pieces%23%23eggs%23%23%0A1%23%23cup%23%23sour+cream%23%23%0A1%23%23cup%23%23Cheddar+cheese%23%23shredded%0A0.5%23%23cup%23%23green+onions%23%23sliced+%28about+4%29%0A0.5%23%23tsp%23%23onion+salt%23%23%0A1%23%23cup%23%23cooked+ham%23%23finely+chopped"

【问题讨论】:

标签: android ios swift string


【解决方案1】:

这是一个经过百分比编码的 URL 字符串(并非所有字符都可以在 url 中发送,因此需要编码)。

使用此方法解码:

if let decodedString = yourString.removingPercentEncoding {
    // Do something with decodedString here
}

This answer 展示了如何将此编码和解码作为String 类型的扩展添加。

【讨论】:

  • 这是错误的 removingPercentEncoding 返回一个可选项。声明:var removingPercentEncoding: String? { get }
  • @LeoDabus 谢谢。我已经更新了使变量可选的答案。
  • Swift 是一种类型推断语言。只是不要显式设置类型并使用if letguard 来解开值。 if let decodedString = yourString.removingPercentEncoding {
  • @LeoDabus 再次感谢。为了简洁起见,我省略了可选绑定,但你说得对,最好在上下文中展示如何使用答案。
  • @Romit - 这个答案可以在 iOS 上的 Swift 中使用,但我知道你也问过关于 Android 的问题。恐怕我对 Android 或 Java 没有经验,但可能有一个等效的函数来编码和解码这样的字符串。