This article explores different ways to replace all occurrences of a substring (or a character) from a string in Kotlin.

The standard solution to replace all occurrences of a “substring” with another string is using the built-in function replace(). Here’s how the code would look like:

Download Code

 
We can also use the replace() function to replace all occurrences of a “character” in the string with another character, as shown below:

Download Code

 
The replace() function is overloaded to accept a Regex. The overloaded version replaces each substring that matches the given regular expression with the specified replacement. It can be used as follows:

Download Code

 
There is another alternative to accomplish this – using the replaceAll() function of the Matcher class to replace each matching substring with the replacement.

Download Code

 
We can also “extract” the substring that needs to be removed/replaced, and call the replace() method on the original string by passing the substring and the replacement.

Download Code

That’s all about replacing all occurrences of a substring (or a character) from a string in Kotlin.