Kotlin Program to Remove All Whitespaces from a String

In Kotlin programming, dealing with strings is a common task. One such task is removing all whitespaces from a string, which can be achieved using various methods. In this article, we’ll explore three different Kotlin Program to Remove All Whitespaces from a String and provide examples with explanations and outputs for each method.

Example 1: Using Regex

Kotlin
import kotlin.text.Regex

fun main() {
    val input = "Hello    World!    This is Kotlin."
    val output = input.replace(Regex("\\s+"), "")
    println(output)
}

Output:

Kotlin
"HelloWorld!ThisisKotlin."

This example utilizes the Regex class from the Kotlin standard library. We define a regular expression pattern \\s+ to match one or more whitespace characters. The replace function then replaces all occurrences of this pattern with an empty string, effectively removing all whitespaces from the input string.

Example 2: Using CharArray

Kotlin
fun main() {
    val input = "Hello    World!    This is Kotlin."
    val charArray = input.toCharArray()
    val output = StringBuilder()

    for (char in charArray) {
        if (!char.isWhitespace()) {
            output.append(char)
        }
    }

    println(output)
}

Output:

Kotlin
"HelloWorld!ThisisKotlin."

In this example, we convert the input string into a character array using toCharArray(). Then, we iterate through each character in the array and append non-whitespace characters to a StringBuilder. This approach allows us to build the output string without whitespaces.

Example 3: Using ReplaceAll

Kotlin
fun main() {
    val input = "Hello    World!    This is Kotlin."
    val output = input.replace(" ", "")
    println(output)
}

Output:

Kotlin
"HelloWorld!ThisisKotlin."

Here, we directly use the replace function on the input string to replace all spaces with an empty string. This method is straightforward and effective for removing whitespaces from a string.

These examples demonstrate different ways to remove whitespaces from a string in Kotlin. Whether you prefer using regular expressions, character arrays, or simple string replacement, Kotlin provides versatile options for string manipulation tasks. Choose the method that best suits your coding style and requirements.