How to replace all occurrences of a sub string in

2019-06-26 08:30发布

问题:

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"

回答1:

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



回答2:

"Good Morning".replace("Morning", "Night")

It's always useful to search for functions in the Kotlin standard library API reference. In this case, you find the replace function in Kotlin.text:

/**
 * Returns a new string with all occurrences of [oldChar] replaced with [newChar].
 */
public fun String.replace(oldChar: Char, newChar: Char, ignoreCase: Boolean = false): String {
    if (!ignoreCase)
        return (this as java.lang.String).replace(oldChar, newChar)
    else
        return splitToSequence(oldChar, ignoreCase ignoreCase).joinToString(separator = newChar.toString())
}


标签: kotlin