Any way to replace characters on Swift String?

前端 未结 21 1900
忘了有多久
忘了有多久 2020-11-22 04:59

I am looking for a way to replace characters in a Swift String.

Example: \"This is my string\"

I would like to replace \" \" with \"+\" to get \

21条回答
  •  不思量自难忘°
    2020-11-22 05:43

    Less happened to me, I just want to change (a word or character) in the String

    So I've use the Dictionary

      extension String{
        func replace(_ dictionary: [String: String]) -> String{
              var result = String()
              var i = -1
              for (of , with): (String, String)in dictionary{
                  i += 1
                  if i<1{
                      result = self.replacingOccurrences(of: of, with: with)
                  }else{
                      result = result.replacingOccurrences(of: of, with: with)
                  }
              }
            return result
         }
        }
    

    usage

    let mobile = "+1 (800) 444-9999"
    let dictionary = ["+": "00", " ": "", "(": "", ")": "", "-": ""]
    let mobileResult = mobile.replace(dictionary)
    print(mobileResult) // 001800444999
    

提交回复
热议问题