Any way to replace characters on Swift String?

2018-12-31 08:59发布

I'm looking for a way to replace characters in a Swift String.

Example: "This is my string"

I'd like to replace with + to get: "This+is+my+string".

How can I achieve this?

标签: ios swift string
15条回答
冷夜・残月
2楼-- · 2018-12-31 09:54

A Swift 3 solution along the lines of Sunkas's:

extension String {
    mutating func replace(_ originalString:String, with newString:String) {
        self = self.replacingOccurrences(of: originalString, with: newString)
    }
}

Use:

var string = "foo!"
string.replace("!", with: "?")
print(string)

Output:

foo?
查看更多
何处买醉
3楼-- · 2018-12-31 09:56

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.

查看更多
伤终究还是伤i
4楼-- · 2018-12-31 09:57

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".

查看更多
登录 后发表回答