[swift] Any way to replace characters on Swift String?

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 "This+is+my+string".

How can I achieve this?

This question is related to swift string

The answer is


you can test this:

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


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)

var str = "This is my string"

print(str.replacingOccurrences(of: " ", with: "+"))

Output is

This+is+my+string

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

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"

var str = "This is my string"
str = str.replacingOccurrences(of: " ", with: "+")
print(str)

Did you test this :

var test = "This is my string"

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

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: "+")

I've implemented this very simple func:

func convap (text : String) -> String {
    return text.stringByReplacingOccurrencesOfString("'", withString: "''")
}

So you can write:

let sqlQuery = "INSERT INTO myTable (Field1, Field2) VALUES ('\(convap(value1))','\(convap(value2)')

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:"+")

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"

You can use this:

let s = "This is my string"
let modified = s.replace(" ", withString:"+")    

If you add this extension method anywhere in your code:

extension String
{
    func replace(target: String, withString: String) -> String
    {
       return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
    }
}

Swift 3:

extension String
{
    func replace(target: String, withString: String) -> String
    {
        return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
    }
}

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"

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?

Less happened to me, I just want to change (a word or character) in the String

So I've use the Dictionary

  extension String{
    func replace(_ dictionary: [String: String]) -> String{
          var result = String()
          var i = -1
          for (of , with): (String, String)in dictionary{
              i += 1
              if i<1{
                  result = self.replacingOccurrences(of: of, with: with)
              }else{
                  result = result.replacingOccurrences(of: of, with: with)
              }
          }
        return result
     }
    }

usage

let mobile = "+1 (800) 444-9999"
let dictionary = ["+": "00", " ": "", "(": "", ")": "", "-": ""]
let mobileResult = mobile.replace(dictionary)
print(mobileResult) // 001800444999

Swift 3 solution based on Ramis' answer:

extension String {
    func withReplacedCharacters(_ characters: String, by separator: String) -> String {
        let characterSet = CharacterSet(charactersIn: characters)
        return components(separatedBy: characterSet).joined(separator: separator)
    }
}

Tried to come up with an appropriate function name according to Swift 3 naming convention.


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.


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


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: "+")

Here is the example for Swift 3:

var stringToReplace = "This my string"
if let range = stringToReplace.range(of: "my") {
   stringToReplace?.replaceSubrange(range, with: "your")
}