Swift String replacingOccurrences()

In this tutorial, we will learn about the Swift string replacingOccurrences() method with the help of examples.

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


import Foundation
var str1 = "bat ball"

// replace b with c print(str1.replacingOccurrences(of: "b",with: "c"))
// Output: cat call

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()

import Foundation 

var text = "Java is awesome. Java is fun."

// all occurrences of "Java" is replaced with "Swift" var new = text.replacingOccurrences(of:"Java", with: "Swift")
// "Python" is not the substring of text , so returns original string var new1 = text.replacingOccurrences(of:"Python", with: "Swift")


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

import Foundation 

var str1 = "abc cba"

// all occurrences of 'a' is replaced with 'z'
print(str1.replacingOccurrences(of: "a", with: "z"))  // zbc cbz

// all occurences of 'L' is replaced with 'J'
print("Lwift".replacingOccurrences(of: "L", with: "S")) // Swift

// "4" not in the string, so returns original string print("Hello".replacingOccurrences(of: "4", with:"J")) // Hello


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
Did you find this article helpful?