Any way to replace characters on Swift String?

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

    Swift 4:

    let abc = "Hello world"
    
    let result = abc.replacingOccurrences(of: " ", with: "_", 
        options: NSString.CompareOptions.literal, range:nil)
    
    print(result :\(result))
    

    Output:

    result : Hello_world
    
    0 讨论(0)
  • 2020-11-22 05:27

    I think Regex is the most flexible and solid way:

    var str = "This is my string"
    let regex = try! NSRegularExpression(pattern: " ", options: [])
    let output = regex.stringByReplacingMatchesInString(
        str,
        options: [],
        range: NSRange(location: 0, length: str.characters.count),
        withTemplate: "+"
    )
    // output: "This+is+my+string"
    
    0 讨论(0)
  • 2020-11-22 05:27

    This is easy in swift 4.2. just use replacingOccurrences(of: " ", with: "_") for replace

    var myStr = "This is my string"
    let replaced = myStr.replacingOccurrences(of: " ", with: "_")
    print(replaced)
    
    0 讨论(0)
  • 2020-11-22 05:28

    Swift 3, Swift 4, Swift 5 Solution

    let exampleString = "Example string"
    
    //Solution suggested above in Swift 3.0
    let stringToArray = exampleString.components(separatedBy: " ")
    let stringFromArray = stringToArray.joined(separator: "+")
    
    //Swiftiest solution
    let swiftyString = exampleString.replacingOccurrences(of: " ", with: "+")
    
    0 讨论(0)
  • 2020-11-22 05:30
    var str = "This is my string"
    
    print(str.replacingOccurrences(of: " ", with: "+"))
    

    Output is

    This+is+my+string
    
    0 讨论(0)
  • 2020-11-22 05:32

    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?
    
    0 讨论(0)
提交回复
热议问题