Swift String replacingOccurrences()

The replacingOccurrences() method replaces each matching occurrence of the old character/text in the string with the new character/text.

Example


replacingOccurrences() Syntax

The syntax of the replaceOccurrences() method is:

string.replacingOccurrences(of old: String, with new: String)

Here, string is an object of the String class.


replacingOccurrences() Parameters

The replacingOccurences() method can take two parameters:

  • old - old substring you want to replace
  • new - new substring which will replace the old substring

replacingOccurrences() Return Value

  • returns a copy of the string where the old substring is replaced with the new substring

Note: If the old substring is not found, it returns the copy of the original string.


Example 1: Swift String replacingOccurrences()

Output

Swift is awesome. Swift is fun.
Java is awesome. Java is fun.

In this program, text.replacingOccurrences(of:"Python", with: "Swift") returns a copy of the original string since "Python" is not a substring of text.


Example 2: Use of replacingOccurrences() with Characters

Output

Swift is awesome. Swift is fun.
Java is awesome. Java is fun.

In this program, we have used the replacingOccurences() function with:

  • str1 - a string variable
  • "Lwift" and "Hello" - string literals