Any way to replace characters on Swift String?

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

    Swift extension:

    extension String {
    
        func stringByReplacing(replaceStrings set: [String], with: String) -> String {
            var stringObject = self
            for string in set {
                stringObject = self.stringByReplacingOccurrencesOfString(string, withString: with)
            }
            return stringObject
        }
    
    }
    

    Go on and use it like let replacedString = yorString.stringByReplacing(replaceStrings: [" ","?","."], with: "+")

    The speed of the function is something that i can hardly be proud of, but you can pass an array of String in one pass to make more than one replacement.

提交回复
热议问题