Any way to replace characters on Swift String?

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

    If you don't want to use the Objective-C NSString methods, you can just use split and join:

    var string = "This is my string"
    string = join("+", split(string, isSeparator: { $0 == " " }))
    

    split(string, isSeparator: { $0 == " " }) returns an array of strings (["This", "is", "my", "string"]).

    join joins these elements with a +, resulting in the desired output: "This+is+my+string".

提交回复
热议问题