Home > Software engineering >  How to replace string characters that are not in a reference list in kotlin
How to replace string characters that are not in a reference list in kotlin

Time:05-14

I have a reference string on which the allowed characters are listed. Then I also have input strings, from which not allowed characters should be replaced with a fixed character, in this example "0".

I can use filter but it removes the characters altogether, does not offer a replacement. Please note that it is not about being alphanumerical, there are ALLOWED non-alphanumerical characters and there are not allowed alphanumerical characters, referenceStr happens to be arbitrary.

var referenceStr = "abcdefg"
var inputStr = "abcqwyzt"
inputStr = inputStr.filter{it in referenceStr}

This yields:

"abc"

But I need:

"abc00000"

I also considered replace but it looks more like when you have a complete reference list of characters that are NOT allowed. My case is the other way around.

CodePudding user response:

Given:

val referenceStr = "abcd][efg"
val replacementChar = '0'
val inputStr = "abcqwyzt[]"

You can do this with a regex [^<referenceStr>], where <referenceStr> should be replaced with referenceStr:

val result = inputStr.replace("[^${Regex.escape(referenceStr)}]".toRegex(), replacementChar.toString())
println(result)

Note that Regex.escape is used to make sure that the characters in referenceStr are all interpreted literally.

Alternatively, use map:

val result = inputStr.map {
    if (it !in referenceStr) replacementChar else it
}.joinToString(separator = "")

In the lambda decide whether the current char "it" should be transformed to replacementChar, or itself. map creates a List<Char>, so you need to use joinToString to make the result a String again.

  • Related