Any way to replace characters on Swift String?

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

    Swift 3 solution based on Ramis' answer:

    extension String {
        func withReplacedCharacters(_ characters: String, by separator: String) -> String {
            let characterSet = CharacterSet(charactersIn: characters)
            return components(separatedBy: characterSet).joined(separator: separator)
        }
    }
    

    Tried to come up with an appropriate function name according to Swift 3 naming convention.

提交回复
热议问题