Remove characters from a string that occurs in another string in Kotlin

Let me preface this by saying that I am really new to Kotlin but a little familiar with Python.

My goal is to remove all occurrences of characters from one string from another string through some function.

I can show you how to do this in Python:

def removechars (s, chars)
    return s.translate(None, chars)

      

And I can use it like this:

print(removechars("The quick brown fox jumped over the sleazy dog!", "qot"))

      

This will give the following output:

The uick brwn fx jumped ver the sleazy dg!     

      

How can I do something like this in Kotlin?

+3


source to share


3 answers


I suggest using filterNot()

in Kotlin:

"Mississippi".filterNot { c -> "is".contains(c)}

      



This should output "Mpp"

.

+4


source


You can use Regex (the equivalent module in Python would be re ):

fun removeChars(s: String, c: String) = s.replace(Regex("[$c]"), "")

println(removeChars("The quick brown fox jumped over the sleazy dog!", "qot"))

      



Output:

The uick brwn fx jumped ver he sleazy dg!

      

+3


source


I'm not familiar with Kotlin, but I would declare both strings and a character variable. Then execute the For ... Next statement with a character assigned in turn to each letter you want to remove and search for the letter (s) in the modified string.

This is probably not the most efficient way to do it, but if you're okay with that little runtime delay, it should work.

0


source







All Articles