How to remove characters present in first string from the second string in Kotlin

4 Answers

0 votes
/**
 * Removes all characters from source that appear in charsToRemove.
 */
fun removeCharacters(
    source: String,
    charsToRemove: String
): String {
    val forbidden = charsToRemove.toSet()

    return source.filterNot { it in forbidden }
}

fun main() {
    val first = "programming language"
    val second = "rogy"

    val result = removeCharacters(second, first)

    println("""First : "$first"""")
    println("""Second: "$second"""")
    println("""Result: "$result"""")
}


/*
run:

First : "programming language"
Second: "rogy"
Result: "y"

*/

 



answered Oct 4 by avibootz
0 votes
/**
 * Removes all characters from source that appear in charsToRemove.
 */
fun removeCharacters(
    source: String,
    charsToRemove: String
): String =
    source.filterNot(charsToRemove.toSet()::contains)

fun main() {
    val first = "programming language"
    val second = "rogy"

    val result = removeCharacters(second, first)

    println("""First : "$first"""")
    println("""Second: "$second"""")
    println("""Result: "$result"""")
}


/*
run:

First : "programming language"
Second: "rogy"
Result: "y"

*/

 



answered Oct 4 by avibootz
0 votes
/**
 * Removes all characters from source that appear in charsToRemove.
 */
fun removeCharacters(
    source: String,
    charsToRemove: String
): String {
    val forbidden = charsToRemove.toSet()
    return source.filterNot(forbidden::contains)
}

fun main() {
    val first = "programming language"
    val second = "rogy"

    val result = removeCharacters(second, first)

    println("""First : "$first"""")
    println("""Second: "$second"""")
    println("""Result: "$result"""")
}


/*
run:

First : "programming language"
Second: "rogy"
Result: "y"

*/

 



answered Oct 4 by avibootz
0 votes
/**
 * Removes all characters from source that appear in charsToRemove.
 */
fun removeCharacters(
    source: String,
    charsToRemove: String
): String {
    val forbidden = charsToRemove.toSet()
    val result = StringBuilder()

    for (ch in source) {
        if (ch !in forbidden) {
            result.append(ch)
        }
    }

    return result.toString()
}

fun main() {
    val first = "programming language"
    val second = "rogy"

    val result = removeCharacters(second, first)

    println("""First : "$first"""")
    println("""Second: "$second"""")
    println("""Result: "$result"""")
}


/*
run:

First : "programming language"
Second: "rogy"
Result: "y"

*/

 



answered Oct 4 by avibootz

Related questions

...