【问题标题】:What is an easier way to replace multiple characters with other characters in a string in swift?用 swift 字符串中的其他字符替换多个字符的更简单方法是什么?
【发布时间】:2018-08-10 01:16:03
【问题描述】:

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

有没有更有效的方法?

【问题讨论】:

    标签: swift character-replacement


    【解决方案1】:

    您正在做的是使用百分比编码手动编码字符串。

    如果是这样,这将对您有所帮助:

    addingPercentEncoding(withAllowedCharacters:)

    通过用百分比编码的字符替换所有不在指定集中的字符,从接收方返回一个新字符串。

    https://developer.apple.com/documentation/foundation/nsstring/1411946-addingpercentencoding

    对于您的具体情况,这应该有效:

    userText.addingPercentEncoding(withAllowedCharacters: .alphanumerics)

    【讨论】:

      【解决方案2】:

      我认为您在使用addPercentEncoding 时会遇到的唯一问题是您的问题指出空格“”应该替换为下划线。对空格“”使用添加百分比编码将返回 %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
      

      【讨论】:

        【解决方案3】:

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

        textInput.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
        

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

        【讨论】:

          猜你喜欢
          • 2013-03-14
          • 2015-03-19
          • 1970-01-01
          • 2011-07-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多