Skip to main content

How to remove all vowels from a string in Kotlin

How to remove all vowels from a string in Kotlin.

Here is a step-by-step tutorial on how to remove all vowels from a string in Kotlin:

  1. Create a function that takes a string as input and returns a new string without any vowels. Let's name this function removeVowels.

  2. Inside the removeVowels function, initialize an empty string to store the result. Let's name this string result.

  3. Loop through each character in the input string using a for loop. Let's name the loop variable char.

for (char in inputString) {
// Code to be added here
}
  1. Check if the current character is a vowel. In Kotlin, we can use the in operator to check if a character is present in a string containing all vowels ("aeiouAEIOU").
if (char.toLowerCase() !in "aeiou") {
// Code to be added here
}
  1. If the current character is not a vowel, append it to the result string using the += operator.
if (char.toLowerCase() !in "aeiou") {
result += char
}
  1. After the loop completes, return the result string.
return result
  1. You can now call the removeVowels function and pass a string as an argument to remove all vowels from it.
val inputString = "Hello, world!"
val resultString = removeVowels(inputString)
println(resultString) // Output: Hll, wrld!

Alternatively, you can use Kotlin's functional programming features to achieve the same result in a more concise way.

  1. Create a function that takes a string as input and returns a new string without any vowels. Let's name this function removeVowels.

  2. Inside the removeVowels function, use the filter function along with a lambda expression to remove all vowels from the input string.

fun removeVowels(inputString: String): String {
return inputString.filter { char ->
char.toLowerCase() !in "aeiou"
}
}
  1. You can now call the removeVowels function and pass a string as an argument to remove all vowels from it.
val inputString = "Hello, world!"
val resultString = removeVowels(inputString)
println(resultString) // Output: Hll, wrld!

That's it! You have successfully removed all vowels from a string in Kotlin using two different approaches.