'How to replace string characters that are not in a reference list in kotlin

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.



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sweeper