Skip to main content

How to remove all occurrences of a specific character from a string in Kotlin

How to remove all occurrences of a specific character from a string in Kotlin.

Here's a step-by-step tutorial on how to remove all occurrences of a specific character from a string in Kotlin.

Step 1: Declare the input string

First, you need to declare the string from which you want to remove the specific character. Let's assume the input string is stored in a variable called inputString.

Step 2: Declare the specific character to remove

Next, you need to declare the specific character that you want to remove from the string. Let's assume the character is stored in a variable called characterToRemove.

Step 3: Using the replace() function

Kotlin provides a built-in function called replace() that allows you to replace characters or substrings in a string. In order to remove a specific character, you can use this function in combination with an empty string.

Here's an example of how you can use the replace() function to remove all occurrences of a specific character:

val result = inputString.replace(characterToRemove.toString(), "")

In the above code, the replace() function is called on the inputString variable. The first argument of the function is characterToRemove.toString(), which converts the specific character to a string. The second argument is an empty string, which means that the specific character will be replaced with nothing.

Step 4: Printing the result

Finally, you can print the resulting string after removing all occurrences of the specific character.

println(result)

Here's the complete code example:

fun main() {
val inputString = "Hello World!"
val characterToRemove = 'o'

val result = inputString.replace(characterToRemove.toString(), "")

println(result)
}

In this example, the input string is "Hello World!" and the specific character to remove is 'o'. The resulting string after removing all occurrences of 'o' is "Hell Wrld!".

You can run this code and see the output for yourself.

That's it! You have successfully removed all occurrences of a specific character from a string in Kotlin.