Home > Enterprise >  How to get the vowels not included in a given string in Kotlin logically?
How to get the vowels not included in a given string in Kotlin logically?

Time:11-10

I want to get the remaining vowels which is not included in given String. My code in Kotlin:

fun main() {
    var line = "ankit"
    var containedVowel = mutableListOf<Char>()
    var vowels = listOf<Char>('a','e','i','o','u')

    for (c in line.toCharArray()) {
        when (c) {
            'a', 'e', 'i', 'o', 'u' -> containedVowel.add(c)
        }
       
   }
   println(vowels.minus(containedVowel))
}

I got the answer but I am unable to get the solution by comparing lists through running loops. I want to get it done logically without using minus() or other inbuilt methods in Kotlin. Any help would be highly appreciated.

CodePudding user response:

Something like the following:

fun main() {
    var line = "ankit"
    var containedVowel = mutableListOf<Char>()
    var vowels = listOf<Char>('a','e','i','o','u')

    for (c in line.toCharArray()) {
        when (c) {
            'a', 'e', 'i', 'o', 'u' -> containedVowel.add(c)
        }
    }

    val missingVowels = mutableListOf<Char>()
    for (char in vowels) {
        if (char !in containedVowel) {
            missingVowels.add(char)
        }
    }

    println(missingVowels)
}

But then again, this could be way simpler if you use Kotlin utility functions.

CodePudding user response:

Without using minus:

val line = "ankit"
val vowelsNotInString = mutableListOf<Char>()

for(vowel in "aeiou") { // or vowel in listOf('a','e','i','o','u') 
    if(vowel !in line)  // or line.indexOf(vowel) == -1
        vowelsNotInString.add(vowel)
}
println(vowelsNotInString)

It's actually hard to come up with such loop based solutions because, with Kotlin, you could have just done this:

val line = "ankit"
println("aeiou".toSet() - line.toSet()) // :)
  • Related