How to remove parentheses and the text inside them from a string in Kotlin

1 Answer

0 votes
/**
 * Remove all parentheses and the text inside them.
 *
 * @param text  The input string
 * @return      The cleaned string
 */
fun removeParenthesesWithContent(text: String): String {
    // Remove parentheses and everything inside them
    val cleaned: String = text.replace(Regex("\\([^)]*\\)"), " ")

    // Collapse multiple spaces into one
    val collapsed: String = cleaned
        .split(Regex("\\s+"))
        .joinToString(" ")

    // Final trim of leading/trailing spaces
    return collapsed.trim()
}

fun main() {
    val str: String =
        "(An) API (API) (is a) (connection) connects (between) computer programs"

    val output: String = removeParenthesesWithContent(str)

    println(output)
}



/*
run:

API connects computer programs

*/

 



answered 1 day ago by avibootz
edited 1 day ago by avibootz

Related questions

...