Any way to replace characters on Swift String?

前端 未结 21 1850
忘了有多久
忘了有多久 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:27

    I think Regex is the most flexible and solid way:

    var str = "This is my string"
    let regex = try! NSRegularExpression(pattern: " ", options: [])
    let output = regex.stringByReplacingMatchesInString(
        str,
        options: [],
        range: NSRange(location: 0, length: str.characters.count),
        withTemplate: "+"
    )
    // output: "This+is+my+string"
    

提交回复
热议问题