Skip to main content

How to remove all digits from a string in Kotlin

How to remove all digits from a string in Kotlin.

Here's a step-by-step tutorial on how to remove all digits from a string in Kotlin:

Step 1: Define the input string

First, you need to define the string from which you want to remove the digits. Let's say we have the following input string:

val inputString = "Hello123World456"

Step 2: Using Regex to remove digits

Kotlin provides a built-in function called replace that allows you to replace parts of a string using regular expressions (regex). In this case, we can use regex to match all the digits in the string and remove them.

val result = inputString.replace("\\d".toRegex(), "")

Here, \\d is the regex pattern that matches any digit. The toRegex() function converts the pattern into a regex object. The replace function then replaces all occurrences of the pattern with an empty string, effectively removing the digits.

Step 3: Print the result

Finally, you can print the resulting string to verify that the digits have been removed:

println(result)

Putting it all together, here's the complete code:

fun main() {
val inputString = "Hello123World456"
val result = inputString.replace("\\d".toRegex(), "")
println(result)
}

When you run this code, the output will be:

HelloWorld

Alternative Approach: Using a loop If you prefer an alternative approach without using regex, you can loop through each character in the string and check if it is a digit. If it is not a digit, you can append it to a new string. Here's an example:

fun main() {
val inputString = "Hello123World456"
var result = ""

for (char in inputString) {
if (!char.isDigit()) {
result += char
}
}

println(result)
}

This code produces the same output as the regex approach:

HelloWorld

That's it! You now know how to remove all digits from a string in Kotlin.