To replace all occurrences of a substring in a string in Kotlin, you can use the replace
function.
In this example,
str
.replace
function on str
with the substring to be replaced and the replacement substring as arguments.replace
function returns a new string with all occurrences of the substring replaced.fun main() {
val str = "Hello World Hello";
val newStr = str.replace("Hello", "Hi");
println(newStr);
}
Hi World Hi
In this example,
str
.replace
function on str
with the substring to be replaced and the replacement substring as arguments.replace
function returns a new string with all occurrences of the substring replaced.fun main() {
val str = "Hello World Hello";
val newStr = str.replace("o", "X");
println(newStr);
}
HellX WXrld HellX
In this tutorial, we learned How to Replace All Occurrences of a Substring in a String in Kotlin language with well detailed examples.