Mustafa Fidan
Mustafa Fidan

Reputation: 173

How do I replace multiple characters in a String?

How do I replace multiple characters in a String?

Like Java's replaceAll(regex:replacement:) function.

str.replaceAll("[$,.]", "") //java code

This answer is very close but I want to change more than one character at the same time.

Upvotes: 13

Views: 24775

Answers (2)

Adil Hussain
Adil Hussain

Reputation: 32113

If you're happy to work with regular expressions, then refer to the accepted answer here. If you're curious as to how you can achieve this without regular expressions, continue reading.

You can use the String.filterNot(predicate:) and Set.contains(element:) functions to define a String.removeAll extension function as follows:

/**
 * @param charactersToRemove The characters to remove from the receiving String.
 * @return A copy of the receiving String with the characters in `charactersToRemove` removed.
 */
fun String.removeAll(charactersToRemove: Set<Char>): String {
    return filterNot { charactersToRemove.contains(it) }
}

You would call on this function as follows: myString.removeAll(setOf('$', '.'))

Upvotes: 2

Zoe - Save the data dump
Zoe - Save the data dump

Reputation: 28238

[$,.] is regex, which is the expected input for Java's replaceAll() method. Kotlin, however, has a class called Regex, and string.replace() is overloaded to take either a String or a Regex argument.

So you have to call .toRegex() explicitly, otherwise it thinks you want to replace the String literal [$,.]. It's also worth mentioning that $ in Kotlin is used with String templates, meaning in regular strings you have to escape it using a backslash. Kotlin supports raw Strings (marked by three " instead of one) which don't need to have these escaped, meaning you can do this:

str = str.replace("""[$,.]""".toRegex(), "")

In general, you need a Regex object. Aside using toRegex() (which may or may not be syntactical sugar), you can also create a Regex object by using the constructor for the class:

str = str.replace(Regex("""[$,.]"""), "")

Both these signal that your string is regex, and makes sure the right replace() is used.

Upvotes: 30

Related Questions