Home > Back-end >  Kotlin - How to remove Letter from Word with Overloading Minus and for Loops?
Kotlin - How to remove Letter from Word with Overloading Minus and for Loops?

Time:10-26

Hallo Coding Friends,

i working since a week on a Kotlin Challange. The Challange is to remove a letter from a Word but it must be with "Operator Overloading" and "for" Loop. I already done it with filter method and it works but is doesnt finish the Challange.

My Programm - Theoretical i know it can be done but practice is another World

operator fun String.minus(filter1: String): String {
    return filter1.minus("l")
}

fun main() {
    val wortHW1 = "Hallo"
    val wortHW2 = "Hallo World"
    for (x in wortHW1) {
        x.minus('l')
    }
}

I really hope you all can help me, stuck since a weeks.

Thx for all your effort

CodePudding user response:

The buildString function is a useful way to write concise String manipulation code. For example:

operator fun String.minus(removedChar: Char): String = buildString {
    for (c in this@minus) {
        if (c != removedChar) append(c)
    }
}

CodePudding user response:

If I understood correctly and given the requiremets this is what you are looking for:

fun main() {
    val wortHW1 = "Hallo"
    val wortHW2 = "Hallo World"
    println(wortHW1.minus('l'))
    println(wortHW2.minus(' '))
}

operator fun String.minus(letterToRemove: Char): String {
    val lettersToKeep: MutableList<Char> = mutableListOf()
    for (letter in this) {
        if (letter != letterToRemove) {
            lettersToKeep.add(letter)
        }
    }

    return lettersToKeep.joinToString("")
}
  • Related