Any way to replace characters on Swift String?

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

    I am using this extension:

    extension String {
    
        func replaceCharacters(characters: String, toSeparator: String) -> String {
            let characterSet = NSCharacterSet(charactersInString: characters)
            let components = self.componentsSeparatedByCharactersInSet(characterSet)
            let result = components.joinWithSeparator("")
            return result
        }
    
        func wipeCharacters(characters: String) -> String {
            return self.replaceCharacters(characters, toSeparator: "")
        }
    }
    

    Usage:

    let token = "<34353 43434>"
    token.replaceCharacters("< >", toString:"+")
    
    0 讨论(0)
  • 2020-11-22 05:39

    Xcode 11 • Swift 5.1

    The mutating method of StringProtocol replacingOccurrences can be implemented as follow:

    extension RangeReplaceableCollection where Self: StringProtocol {
        mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<String.Index>? = nil) {
            self = .init(replacingOccurrences(of: target, with: replacement, options: options, range: searchRange))
        }
    }
    

    var name = "This is my string"
    name.replaceOccurrences(of: " ", with: "+")
    print(name) // "This+is+my+string\n"
    
    0 讨论(0)
  • 2020-11-22 05:39

    Here's an extension for an in-place occurrences replace method on String, that doesn't no an unnecessary copy and do everything in place:

    extension String {
        mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], locale: Locale? = nil) {
            var range: Range<Index>?
            repeat {
                range = self.range(of: target, options: options, range: range.map { self.index($0.lowerBound, offsetBy: replacement.count)..<self.endIndex }, locale: locale)
                if let range = range {
                    self.replaceSubrange(range, with: replacement)
                }
            } while range != nil
        }
    }
    

    (The method signature also mimics the signature of the built-in String.replacingOccurrences() method)

    May be used in the following way:

    var string = "this is a string"
    string.replaceOccurrences(of: " ", with: "_")
    print(string) // "this_is_a_string"
    
    0 讨论(0)
  • 2020-11-22 05:41

    A category that modifies an existing mutable String:

    extension String
    {
        mutating func replace(originalString:String, withString newString:String)
        {
            let replacedString = self.stringByReplacingOccurrencesOfString(originalString, withString: newString, options: nil, range: nil)
            self = replacedString
        }
    }
    

    Use:

    name.replace(" ", withString: "+")
    
    0 讨论(0)
  • 2020-11-22 05:41
    var str = "This is my string"
    str = str.replacingOccurrences(of: " ", with: "+")
    print(str)
    
    0 讨论(0)
  • 2020-11-22 05:42

    Here is the example for Swift 3:

    var stringToReplace = "This my string"
    if let range = stringToReplace.range(of: "my") {
       stringToReplace?.replaceSubrange(range, with: "your")
    } 
    
    0 讨论(0)
提交回复
热议问题