Skip to main content

How to remove all non-printable characters from a string in Kotlin

How to remove all non-printable characters from a string in Kotlin.

Here is a step-by-step tutorial on how to remove all non-printable characters from a string in Kotlin.

Step 1: Create a function

To begin, let's create a function that will take a string as input and return a new string with all non-printable characters removed. We will name this function removeNonPrintableCharacters.

fun removeNonPrintableCharacters(input: String): String {
// code to be added here
}

Step 2: Define the non-printable characters

Next, we need to define the set of non-printable characters that we want to remove. In Kotlin, we can represent this set as a regular expression pattern. Here, we will use the pattern \p{Cntrl} to match all control characters.

val nonPrintablePattern = "\\p{Cntrl}".toRegex()

Step 3: Remove non-printable characters

Now, let's use the replace function to remove all non-printable characters from the input string. We will pass the nonPrintablePattern as the first argument and an empty string as the second argument to replace the matched characters with nothing.

fun removeNonPrintableCharacters(input: String): String {
val nonPrintablePattern = "\\p{Cntrl}".toRegex()
return input.replace(nonPrintablePattern, "")
}

Step 4: Test the function

To ensure that our function works correctly, let's test it with a few examples.

fun main() {
val input1 = "Hello\tWorld!" // string with a tab character
val input2 = "Hello\nWorld!" // string with a newline character
val input3 = "Hello\u0007World!" // string with a bell character

println(removeNonPrintableCharacters(input1)) // Output: HelloWorld!
println(removeNonPrintableCharacters(input2)) // Output: HelloWorld!
println(removeNonPrintableCharacters(input3)) // Output: HelloWorld!
}

Step 5: Understand the code

In the removeNonPrintableCharacters function, we first define a regular expression pattern to match all control characters. Then, we use the replace function to replace all matched characters with an empty string, effectively removing them from the input string.

By testing the function with different input strings, we can see that it successfully removes all non-printable characters, resulting in a clean output.

And that's it! You now have a function to remove all non-printable characters from a string in Kotlin. Feel free to use this function in your own projects to sanitize user input or manipulate strings as needed.