Replace matching characters of a String in Swift

In this Swift programming tutorial, you are going to learn how to replace each matching occurrence of the old character or substring in the string with the new character or substring.

In Swift, we can use the replacingOccurrences(of:with:) method that can help us to replace the old string and return a new string with the specified characters replaced with the provided characters.

The replacingOccurrences() method is part of the Foundation library. hence, we have to import this library to work with this method.

Below is an example of replacing characters of a string using the replacingOccurrences():

import Foundation

var originalString = "This should be a slug"

var newString = originalString.replacingOccurrences(of: " ",with: "+")




In the above code, we are replacing all the whitespace (” “) with “+”. The code replaces all the whitespaces with our provided “+” sign.

Now see another example where we are replacing a specific substring using the same method:

import Foundation

var originalString = "I Love Python programming"

var newString = originalString.replacingOccurrences(of: "Python",with: "Swift")



I Love Swift programming

As you can see from the output of each example, we have successfully able to replace a specific character or substring using the Swift replacingOccurrences() method.