Any way to replace characters on Swift String?

前端 未结 21 1767
忘了有多久
忘了有多久 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 test this:

    let newString = test.stringByReplacingOccurrencesOfString(" ", withString: "+", options: nil, range: nil)

    0 讨论(0)
  • 2020-11-22 05:48

    This answer has been updated for Swift 4 & 5. If you're still using Swift 1, 2 or 3 see the revision history.

    You have a couple of options. You can do as @jaumard suggested and use replacingOccurrences()

    let aString = "This is my string"
    let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)
    

    And as noted by @cprcrack below, the options and range parameters are optional, so if you don't want to specify string comparison options or a range to do the replacement within, you only need the following.

    let aString = "This is my string"
    let newString = aString.replacingOccurrences(of: " ", with: "+")
    

    Or, if the data is in a specific format like this, where you're just replacing separation characters, you can use components() to break the string into and array, and then you can use the join() function to put them back to together with a specified separator.

    let toArray = aString.components(separatedBy: " ")
    let backToString = toArray.joined(separator: "+")
    

    Or if you're looking for a more Swifty solution that doesn't utilize API from NSString, you could use this.

    let aString = "Some search text"
    
    let replaced = String(aString.map {
        $0 == " " ? "+" : $0
    })
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题