【问题标题】:How to delete \ (backslash) from string swift如何从字符串swift中删除\(反斜杠)
【发布时间】:2016-08-30 16:48:54
【问题描述】:

字符串中的反斜杠有问题。

当我用这段代码创建一个字符串时:

 let url = webProtocol + siteHost + "/tables/coupon?$expand=source&$filter=Source/Name eq '" + category + "'&" + siteApi

我希望这个网址

https://swoup.azurewebsites.net/tables/coupon?$expand=source&$filter=Source/Name eq 'Recommended'&ZUMO-API-VERSION=2.0.0

但我明白了

https://swoup.azurewebsites.net/tables/coupon?$expand=source&$filter=Source/Name eq \'Recommended\'&?ZUMO-API-VERSION=2.0.0

我尝试使用

删除它们
stringByReplacingOccurrencesOfString("\\", withString: "")

但这无济于事。我也尝试在 ' 之前添加反斜杠,但它没有帮助。

【问题讨论】:

  • 为什么你期望的 URL 中有空格?
  • 你对url编码了吗?
  • 提供完整的问题,webProtocolsiteHostcategorysiteApi 未定义。提供minimal reproducible example,强调完成。
  • 正如 Aaron 指出的,您尝试创建的 URL 无效,空格和您使用的其他一些字符无效。在此处检查 URL 中的有效字符 -> stackoverflow.com/questions/1547899/…
  • 您在哪里/如何记录 URL?许多工具显示转义版本并添加反斜杠。

标签: ios swift xcode string encoding


【解决方案1】:

根据您的问题尚不清楚,但我相信反斜杠实际上不在字符串中,而是由 XCode 打印的。例如,在 Playground 中输入以下内容:

let siteApi="test=123"
let category="Category1"
let webProtocol="https://"
let siteHost="www.testme.com"
let url = webProtocol + siteHost + "/tables/coupon?$expand=source&$filter=Source/Name eq '" + category + "'&" + siteApi
print( url)

你会看到输出不包含反斜杠。

https://www.testme.com/tables/coupon?$expand=source&$filter=Source/Name eq 'Category1'&test=123

【讨论】:

  • 您没有使用反斜杠,在他的代码类别中填写了\'\' 是字符串中的特殊代码,表示单个撇号。问题归结为任何填写类别的内容都必须做\\\'
  • 这太令人困惑了。这是一个不完整的示例,混合引号使其难以阅读。希望他能发布完整的代码,我们可以更好地了解问题出在哪里。
  • 确实令人困惑
  • 看看反斜杠的位置,它在第一个单引号之前,所以我认为问题不是类别变量的内容。
  • 我认为单独的'在字符串文字中是无效的,需要\'
【解决方案2】:

使用 NSURLComponents 和 NSURLQueryItem 来构建 URL,而不是字符串连接。

let components = NSURLComponents()
components.scheme = "https"
components.host = "swoup.azurewebsites.net"
components.path = "/tables/coupon"
let category = "Recommended"
let expand = NSURLQueryItem(name: "expand", value: "source")
let filter = NSURLQueryItem(name: "filter", value: "Source/Name eq '\(category)'")
let api = NSURLQueryItem(name:"ZUMO-API-VERSION", value:"2.0.0")
components.queryItems = [expand, filter, api]

给你这个来自components.URL的网址:

https://swoup.azurewebsites.net/tables/coupon?expand=source&filter=Source/Name%20eq%20\'Recommended\'&ZUMO-API-VERSION=2.0.0

【讨论】:

    【解决方案3】:

    错误出现在未显示的变量中。

    有了这个例子完整的(?)代码示例:

    let webProtocol = "https://"
    let siteHost = "swoup.azurewebsites.net"
    let category = "Recommended"
    let siteApi = "ZUMO-API-VERSION=2.0.0"
    let url = webProtocol + siteHost + "/tables/coupon?$expand=source&$filter=Source/Name eq '" + category + "'&" + siteApi
    print (url)
    

    输出
    https://swoup.azurewebsites.net/tables/coupon?$expand=source&$filter=Source/Name eq 'Recommended'&ZUMO-API-VERSION=2.0.0

    没有\

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      相关资源
      最近更新 更多