Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all occurrences of a sub string in kotlin

Tags:

kotlin

How to replace a part of a string with something else in Kotlin?

For example, changing "good morning" to "good night" by replacing "morning" with "night"

like image 252
Abhipso Ghosh Avatar asked May 26 '17 08:05

Abhipso Ghosh


People also ask

How do you replace a substring in Kotlin?

The basic String Replace method in Kotlin is String. replace(oldValue, newValue). ignoreCase is an optional argument, that could be sent as third argument to the replace() method.

How do I change the value of a string in Kotlin?

Strings are immutable in Kotlin. That means their values cannot be changed once created. To replace the character in a string, you will need to create a new string with the replaced character.

How do I remove a substring from a string in Kotlin?

Since strings are immutable in Kotlin, we can't remove characters from it. However, we can create a new string with the first n characters removed. This can be done using the substring() function with the starting index n , which creates a substring starting from position n till its end.


1 Answers

fun main(args: Array<String>) {
  var a = 1
  // simple name in template:
  val s1 = "a is $a" 

  a = 2
  // arbitrary expression in template:
  val s2 = "${s1.replace("is", "was")}, but now is $a"
  println(s2)
}

OUPUT: a was 1, but now is 2

like image 109
Ronak Thakkar Avatar answered Oct 11 '22 18:10

Ronak Thakkar