Any way to replace characters on Swift String?

前端 未结 21 1903
忘了有多久
忘了有多久 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条回答
  •  旧时难觅i
    2020-11-22 05:39

    Here's an extension for an in-place occurrences replace method on String, that doesn't no an unnecessary copy and do everything in place:

    extension String {
        mutating func replaceOccurrences(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], locale: Locale? = nil) {
            var range: Range?
            repeat {
                range = self.range(of: target, options: options, range: range.map { self.index($0.lowerBound, offsetBy: replacement.count)..

    (The method signature also mimics the signature of the built-in String.replacingOccurrences() method)

    May be used in the following way:

    var string = "this is a string"
    string.replaceOccurrences(of: " ", with: "_")
    print(string) // "this_is_a_string"
    

提交回复
热议问题