Replace all occurrences of a substring (or a char) in Kotlin
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:
|
1 2 3 4 5 6 7 |
fun main() { var str = "ABCABD" val target = "AB" str = str.replace(target, "") println(str) // CD } |
We can also use the replace() function to replace all occurrences of a “character” in the string with another character, as shown below:
|
1 2 3 4 5 6 7 |
fun main() { var str = "A|B|C|D|E" val target = '|' str = str.replace(target, ',') println(str) // A,B,C,D,E } |
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:
|
1 2 3 4 5 6 7 |
fun main() { var str = "A|B|C|D|E" val regex = "[^\\p{Alpha}+]" str = str.replace(regex.toRegex(), ", ") println(str) // A, B, C, D, E } |
There is another alternative to accomplish this – using the replaceAll() function of the Matcher class to replace each matching substring with the replacement.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.regex.Matcher import java.util.regex.Pattern fun replace(str: String?, target: String?, replacement: String?): String { return Pattern.compile(target, Pattern.LITERAL).matcher(str) .replaceAll(Matcher.quoteReplacement(replacement)) } fun main() { var str = "ABCABD" val target = "AB" val replacement = "" str = replace(str, target, replacement) println(str) // CD } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun replace(word: String, replacement: String): String { // the beginning index, inclusive. val beginIndex = word.indexOf('(') + 1 // the ending index, exclusive. val endIndex = word.lastIndexOf(')') // get substring that needs to be replaced val target = word.substring(beginIndex, endIndex) // replace the target with the replacement return word.replace(target, replacement) } fun main() { val word = "Java (SE Development Kit) 8" println(replace(word, "SDK")) // Java (SDK) 8 } |
That’s all about replacing all occurrences of a substring (or a character) from a string in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)