4

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

My goal is to remove all the occurrences of the characters in one string from another string via some sort of function.

I can show you how I would 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"))

It would give this output :

The uick brwn fx jumped ver the sleazy dg!     

How can I something similar in Kotlin?

3 Answers 3

4

I suggest using filterNot() in Kotlin:

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

This should output "Mpp".

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

Comments

4

You can use Regex (the equivlant 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!

1 Comment

I don't know Kotlin, but it doesn't look like you're escaping the characters. If I set chars = "[]\" the regex will be [[]\].
0

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

It probably isn't the most efficient way of doing it but if you're okay with that slight delay in run time, it should work.

Comments

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.