Replace all occurrences of search string with replacement string in Swift

To replace all the occurrences of a search string with a specified replacement string in a given string in Swift, you can use String replacingOccurrences() method.

For example, if str is the given string, and we would, like to convert to replace the occurrences of searchString with a replacementString, then the syntax would be

str.replacingOccurrences(of: searchString, with: replacementString)

The function returns a new string with the searchString replaced with replacementString.

Examples

ADVERTISEMENT

1. Replace “apple” with “cherry” in given string

In this example, we will take a string value in str, and replace all the occurrences of "apple" search string with the "cherry" replacement string.

main.swift

import Foundation

let str = "apple is red. apple is good."
let searchString = "apple"
let replacementString = "cherry"

let resultStr = str.replacingOccurrences(of: searchString, with: replacementString)

print(resultStr)

Output

Swift - Replace all occurrences of search string with replacement string

Conclusion

In this Swift Tutorial, we have seen how to replace all the occurrences of a given search string with a replacement string using replacingOccurrences() method of String class instance.