Reputation: 101
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?
Upvotes: 4
Views: 3459
Reputation: 325
I suggest using filterNot()
in Kotlin:
"Mississippi".filterNot { c -> "is".contains(c)}
This should output "Mpp"
.
Upvotes: 4
Reputation: 112
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.
Upvotes: 0
Reputation: 22370
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!
Upvotes: 4