Any way to replace characters on Swift String?

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

    You can use this:

    let s = "This is my string"
    let modified = s.replace(" ", withString:"+")    
    

    If you add this extension method anywhere in your code:

    extension String
    {
        func replace(target: String, withString: String) -> String
        {
           return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
        }
    }
    

    Swift 3:

    extension String
    {
        func replace(target: String, withString: String) -> String
        {
            return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
        }
    }
    

提交回复
热议问题