CodeGym /Courses /Kotlin SELF /Cleaning “dirty text”

Cleaning “dirty text”

Kotlin SELF
Level 44, Lesson 4
Available

1. What is “dirty text”

When you read a file and get a String, you really want to think: “That’s it, it’s already text; next come ordinary split, trim, comparisons.” But the outside world loves surprises: the file could have come from Windows, from Excel, from someone else’s editor, from an old system, from an archive. And it may contain “ugly bits” that you can’t see with your eyes but that break the logic.

“Dirty text” in the context of today’s lecture is text that is readable overall, but contains hidden technical effects. The two most common ones are: a BOM at the beginning (it interferes with the first word/header) and different line breaks ("\n" vs "\r\n"), which break “line-based” parsing if you expected one specific format.

So that parsing doesn’t turn into fortune-telling, we’ll follow a discipline: first make the input predictable, and only then parse the data.

2. Cleaning plan

If yesterday’s file work already made you catch yourself thinking, “Why am I reading text, yet still thinking about bytes?”, today that inner conflict ends with a peace treaty. We’ll honestly acknowledge: a file starts with bytes, and some problems (for example BOM) are simpler and more reliable to solve precisely at the byte level.

It’s useful to keep the scheme in mind as a mini pipeline:

flowchart LR
    A["readBytes()"] --> B[remove UTF-8 BOM]
    B --> C["String(bytes, UTF_8)"]
    C --> D[normalizeNewlines]
    D --> E[parse / split / comparisons]

Notice we clean twice, but at different levels: BOM is more convenient to cut out as bytes, while line breaks are handled as text (because they are sequences of characters in a string).

3. Working with bytes and the BOM

Read the file as bytes

Before “fixing” a file, it’s useful to be able to quickly check: are there any suspicious bytes at all? Especially in the first 3–4 bytes, where the UTF‑8 BOM may be sitting. For this we need readBytes(). It returns a ByteArray — a fixed-size array of bytes, which we already know how to index into.

Mini example: “look at the first bytes”:

import java.io.File

fun main() {
    val bytes = File("data/input.txt").readBytes()
    val preview = bytes.take(8).joinToString(separator = " ") { it.toUByte().toString() }
    println("firstBytes=$preview") // e.g.: firstBytes=239 187 191 105 100 44 110 97
}

Comment: I use toUByte() so the output is “human-friendly” (0..255), rather than negative bytes. This is purely for diagnostics.

Remove the UTF‑8 BOM

Now we move on to the main “invisible culprit”. A UTF‑8 BOM is three bytes at the very start of the file: EF BB BF (in hex). In Kotlin, a byte is signed (-128..127), so we compare via 0xEF.toByte() and so on; otherwise it gets confusing.

A careful BOM removal function should do two things: check for a BOM and only then cut off the first three bytes. If there is no BOM, it should return the original bytes unchanged. We do not “cut just in case”, because that could eat a real first character.

fun removeUtf8Bom(bytes: ByteArray): ByteArray {
    val hasBom =
        bytes.size >= 3 &&
        bytes[0] == 0xEF.toByte() &&
        bytes[1] == 0xBB.toByte() &&
        bytes[2] == 0xBF.toByte()

    return if (hasBom) bytes.copyOfRange(3, bytes.size) else bytes
}

There are two practical nuances here.

First, copyOfRange(3, bytes.size) creates a new array and copies data. That’s fine: we “clean the input” and get a new version. This approach is easier to understand than trying to “shift” an array in place. Also, arrays are fixed-size, so you can’t “cut off the beginning without copying” unless you use trickier constructs.

Second, we check bytes.size >= 3, otherwise accessing bytes[2] will crash with an index error. This is that rare case where a couple of extra characters in a condition save your evening.

Decode to a UTF‑8 string

After removing the BOM (if it was present), you can safely turn the bytes into a string. And here it’s very important not to fall back to the “default charset”. We’ve already agreed that in a well-behaved application the charset is part of the contract, so you specify it explicitly.

Mini decoding function:

fun decodeUtf8(bytes: ByteArray): String {
    return String(bytes, Charsets.UTF_8)
}

And a small “before/after” check (with training data you can sometimes literally see the difference):

import java.io.File

fun main() {
    val rawBytes = File("data/input.txt").readBytes()
    val cleanBytes = removeUtf8Bom(rawBytes)

    println("rawSize=${rawBytes.size}")      // rawSize=...
    println("cleanSize=${cleanBytes.size}")  // cleanSize=... (may be smaller by 3)
}

4. Normalizing line breaks

Even if you defeat the BOM, line breaks can still ruin your mood. On Unix-like systems, "\n" (LF) is more common. On Windows, it’s usually "\r\n" (CRLF). Sometimes, from “ancient” sources, you can even encounter a lone "\r". Visually, in an editor you see a “new line”, but in the data these are different character sequences.

Why does this matter? Because you often do something like text.split("\n") or look for the first line via indexOf('\n'). If there is "\r\n" inside, the lines will have a trailing "\r", and then comparisons suddenly break: "id" is not equal to "id\r".

Normalization is converting all variants into one. Most often, people choose "\n", because it’s shorter and more familiar in code.

fun normalizeNewlines(text: String): String {
    val step1 = text.replace("\r\n", "\n")
    return step1.replace("\r", "\n")
}

The replacement order matters here: first "\r\n", then the single "\r". Otherwise you can accidentally turn "\r\n" into "\n\n" (first you replaced "\r" with "\n", and then the second part also produced "\n").

Mini demo: “why this breaks comparisons”:

fun main() {
    val windowsLine = "id,name\r\n"
    val parts = windowsLine.split("\n")

    println(parts[0] == "id,name") // false (actually "id,name\r")
}

And after normalization everything becomes boringly correct (and “boringly correct” is a compliment for data input):

fun main() {
    val windowsLine = "id,name\r\n"
    val normalized = normalizeNewlines(windowsLine)

    println(normalized.split("\n")[0] == "id,name") // true
}

5. The readCleanUtf8 function

Now we’ll assemble the pipeline into one handy function so the rest of the code (parsing, commands, reports) doesn’t think about BOM and line breaks at all. This is an important style: bring “dirty input” to a standard form at the boundary, and work with clean data inside the program.

import java.io.File

fun readCleanUtf8(file: File): String {
    val rawBytes = file.readBytes()
    val bytesNoBom = removeUtf8Bom(rawBytes)

    val rawText = String(bytesNoBom, Charsets.UTF_8)
    return normalizeNewlines(rawText)
}

Pay attention to the variable names. rawBytes, bytesNoBom, rawText — this is not “wordy fluff”, but a way to avoid getting lost across levels. When you open the code a week later, you won’t have to guess which step you’re on and whether “we’ve already cleaned the input”.

6. Example: reading a task list

So this lecture isn’t pure theory, let’s continue a simple console story: “we have a file with a list of tasks, one task per line”. This is very similar to how many CLI utilities store data in plain text.

Let’s imagine the file format data/tasks.txt:

  • the first line is the header TASKS
  • then task lines follow
  • ignore empty lines

The problem we want to prevent: if the file was created by something that added a BOM, the header becomes "\uFEFFTASKS" (or an equivalent via bytes), and the header check breaks.

Let’s make a function that takes text and returns a list of tasks. (Yes, this is List<String> — we’ve already covered collections, and here they are very appropriate.)

fun firstLine(text: String): String {
    val idx = text.indexOf('\n')
    return if (idx == -1) text else text.substring(0, idx)
}

Now a simple parse (note: we don’t use lists in the explanation, but in code doing this without collections would be artificially hard):

fun parseTasks(cleanText: String): List<String> {
    val lines = cleanText.split('\n')
    if (lines.isEmpty() || lines[0] != "TASKS") return emptyList()

    return lines.drop(1).map { it.trim() }.filter { it.isNotEmpty() }
}

And we wire everything together in main:

import java.io.File

fun main() {
    val file = File("data/tasks.txt")
    val text = readCleanUtf8(file)
    val tasks = parseTasks(text)

    println("tasksCount=${tasks.size}") // e.g.: tasksCount=3
}

The “magic” here is that parseTasks receives already clean text. It doesn’t know and shouldn’t know about BOM, bytes, and "\r\n". This is good separation of responsibilities: the cleaning function is responsible for the environment, the parsing function is responsible for meaning.

7. Why it’s better to clean the BOM at the byte level

Sometimes there’s a temptation: “Let’s just read the text and then do if (text.startsWith("\uFEFF")) text.substring(1).” And that does sometimes work. But the byte-level approach is usually more stable for two reasons.

The first reason is that BOM is inherently a byte marker. If you first decoded bytes “somehow” (or even correctly) and then try to guess what BOM turned into in the string, you’ve already taken a step back toward “symptoms” rather than the “cause”.

The second reason is more practical: bytes let you say precisely “yes, this is exactly EF BB BF”, and avoid touching the data if it is not a BOM. With strings, unexpected “similar-looking characters” sometimes appear, and debugging turns into a performance of “why is my first character invisible?”

At the same time, knowing about '\uFEFF' is useful as a diagnostic trace: if you printed a string somewhere and see strange behavior in the first character, it’s a good hint. But it’s more convenient to “treat” it at the byte level.

8. Typical mistakes

Mistake No. 1: doing split("\n") first, and normalizing line breaks afterwards.
This order almost guarantees you’ll get strings like "TASKS\r" or "id,name\r", after which phantom comparison errors begin. You must normalize line breaks before any “line-based” splitting; otherwise you bake the problem into your data structure.

Mistake No. 2: “let’s cut off the first character, maybe it’s a BOM”.
This is a classic attempt to fix an unknown problem by “removing something”. If there was no BOM, you will corrupt the data: the first letter of the header disappears, and you create a bug where none existed. Remove the BOM only after checking the signature (at the byte level) or the specific "\uFEFF" at the start of the string.

Mistake No. 3: mixing data levels in a single variable named text.
When the same variable alternately means “raw bytes”, “string as read”, “string after BOM removal”, “string after normalization” — you lose control very quickly. The code starts to look short, but becomes fragile: you don’t understand what state the data is in right now. Different names (rawBytes, bytesNoBom, rawText, cleanText) make the code a couple lines longer, but save hours.

Mistake No. 4: forgetting bytes.size >= 3 when checking for a BOM.
Yes, files are sometimes empty. Or contain 1–2 bytes (for example, someone created a stub). If you access bytes[2] without checking, you’ll get an index crash and start looking for “charset issues”, even though the real issue is array bounds. And arrays, as we already know, love their bounds.

Mistake No. 5: assuming that if it “looks fine in the editor”, then there’s no need to encode and clean.
An editor is also a program that makes choices: which charset to apply and how to display line breaks. Your program must be robust without the editor’s hints. That’s why cleaning input is not paranoia, but a normal engineering habit.

1
Task
Kotlin SELF, level 44, lesson 4
Locked
Normalized line breaks
Normalized line breaks
1
Task
Kotlin SELF, level 44, lesson 4
Locked
Trim extra bytes
Trim extra bytes
1
Task
Kotlin SELF, level 44, lesson 4
Locked
Clean read
Clean read
1
Task
Kotlin SELF, level 44, lesson 4
Locked
Missions list
Missions list
1
Survey/quiz
Encodings, level 44, lesson 4
Unavailable
Encodings
Encodings
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION