0

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.

9
  • 1
    Quick solution. Commented May 13, 2022 at 11:49
  • Exactly what wanted! Thanks a lot. Commented May 13, 2022 at 11:50
  • 1
    Alternative quick solution: inputStr.replace("[^$referenceStr]".toRegex(), "0") (caveat: it only works with restrictions, e.g. referenceStr must not contain "]") Commented May 13, 2022 at 11:56
  • @uğur-dinç Are you sure? This solution replace characters on current iteration. For example if we have val referenceStr = "zbcdefg" the result will be 0bc000z0, It is correct approach for solving you issue? Commented May 13, 2022 at 11:58
  • @Sky yes exactly :) That was great help thanks a lot. Commented May 13, 2022 at 12:04

1 Answer 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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is it just me or does the Kotlin stdlib seem a bit inconsistent that String.filter returns String, but String.map returns List?
@k314159 Note that this is using CharSequence.map and String.filter. String.map doesn't actually exist. But it is a bit inconsistent, isn't it? I think there should be a String.map extension that returns a String too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.