Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 134 ยท Text, Files and Time

Text Processing

Learn practical Kotlin text processing - split, lines, trim, windowed, chunked, word counts, parsing CSV-like text and Char functions - with runnable examples and common pitfalls.

Most programs spend a surprising amount of time handling text: reading a configuration file, splitting a log line into fields, counting words, cleaning up user input, turning "name: value" pairs into data. Kotlin's standard library has a rich set of functions for this, and once you know them well you rarely need a loop that pokes at characters one by one.

This lesson is a tour of the everyday tools: breaking text into pieces (split, lines), cleaning it (trim, removePrefix), looking at it in windows and chunks, counting words, parsing small formats such as CSV-like text and key=value files, and working with individual characters. The strings lesson (Strings) covers the basics; here we put the tools to work. For pattern-based searching see Regular Expressions.

Splitting text

split cuts a string at every occurrence of a delimiter and returns a List<String>. It accepts one or several delimiter strings, a Char, or a Regex. Two details matter: consecutive delimiters give empty strings, and limit keeps the remainder together.

Kotlin split, with and without surprises

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The list "a,,c,".split(",") has four elements: a, an empty string, c and another empty string at the end. Whitespace-separated text is the classic trap: splitting on a single space turns every extra space into an empty element, so use a Regex for \s+, or trim first and filter. When you only need the part before or after one delimiter, substringBefore and substringAfter are simpler and do not allocate a list.

Lines

Text from files and user input contains line breaks, and the break might be \n (Unix), \r\n (Windows) or, rarely, \r. lines() handles all of them; splitting on "\n" leaves a stray \r at the end of every line of a Windows file.

Kotlin lines versus split on newline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

wrong has lengths 6, 7 and 5: the first two entries carry an invisible \r. lines() gives 5, 6 and 5. trimIndent() removes the common leading whitespace of a raw string, which is the standard way to write multi-line text inside indented code. For large texts, lineSequence() is lazy and does not build the whole list at once.

Cleaning: trim, prefix and suffix

User input is untidy. trim() removes whitespace at both ends (trimStart, trimEnd for one side), and trim { it == '-' } takes a predicate for other characters. removePrefix, removeSuffix and removeSurrounding strip a known piece only if it is there. ifBlank and ifEmpty provide a default.

Kotlin Cleaning text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Remember that Kotlin strings are immutable, so every one of these functions returns a new string; writing name.trim() without using the result changes nothing. Also note lowercase() (which replaced the deprecated toLowerCase()).

Windows and chunks

Sometimes you care about neighbouring characters or equal-sized blocks. windowed(size, step) slides a window over the text, chunked(size) splits it into non-overlapping blocks, and zipWithNext pairs each character with the one after it. They work on strings directly and can take a transform lambda.

Kotlin windowed, chunked and zipWithNext

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

windowed(3) on seven characters returns five windows, because only five positions leave room for three characters. With partialWindows = true the shorter windows at the end are included as well. chunked always covers the whole string, so its last piece may be short.

Counting words

Counting how often each word occurs is the classic first text-processing program. The steps are: split into words, normalize them, then group and count. groupingBy { ... }.eachCount() does the last two steps in one call.

Kotlin Word frequencies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice the explicit tie-break (thenBy { it.key }). Without it, words with equal counts come out in whatever order the map keeps, which is fragile to rely on. Splitting on "anything that is not a letter" is a deliberate choice: it handles punctuation like dog. and away! without a separate cleaning step. For real languages with accents, use \p{L} instead of a-z.

Parsing CSV-like text

Small data formats are a good fit for the functions above. The recipe: split into lines, drop the header and blank lines, split each line into fields, convert, and report problems clearly. Using toIntOrNull() instead of toInt() lets you handle bad input without exceptions.

Kotlin Parsing a small CSV

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Two lines are rejected, each with a clear message, and the program keeps going. This hand-rolled approach is fine for simple data. Real CSV allows quoted fields that contain commas ("Smith, John"), and a plain split(",") breaks on them. When your data can contain quotes, use a proper CSV library or write a small state-machine parser instead of stretching split.

Parsing key=value text

Configuration files, HTTP headers and query strings are all "key, separator, value". substringBefore/substringAfter or split with limit = 2 do the job, and associate builds a map.

Kotlin Parsing key=value settings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

limit = 2 is the important part: greeting = hello = world has two equals signs, and the value must keep the second one. The map preserves the file order because associate returns a LinkedHashMap. The destructuring val (key, value) = ... works on lists, and would throw IndexOutOfBoundsException if the list had fewer than two elements; that is why the line '=' in it is filtered first.

Working with characters

A Char is a single UTF-16 code unit. The Char type has functions to classify and convert it: isDigit(), isLetter(), isLetterOrDigit(), isWhitespace(), isUpperCase(), uppercaseChar(), lowercaseChar() and digitToInt(). Arithmetic on characters works too: 'a' + 2 is 'c', and 'e' - 'a' is 4.

Kotlin Character functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Use .mod(26) rather than % for the wrap-around: % can return a negative number for a negative shift, while mod always returns a non-negative result for a positive divisor. digitToInt() throws IllegalArgumentException for a character that is not a digit, so use digitToIntOrNull() for input you do not trust. And replaceFirstChar is the modern replacement for the deprecated capitalize().

A Char is not always one visible character. Emoji and many characters from other scripts are stored as two Chars (a surrogate pair), and an accented letter can be a letter plus a combining mark. "๐Ÿ‘".length is 2. For text that may contain such characters, use codePoints() or the java.text.BreakIterator class instead of indexing by Char.

Building output

When you assemble text, prefer buildString, joinToString and padStart/padEnd over repeated + in a loop. This is covered in String Templates and Formatting; here is a short example that prints a neat table from parsed data.

Kotlin A neat text table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Pitfalls to remember

  • Empty pieces: split keeps empty strings between and after delimiters. Filter them or use a regex.
  • Line endings: use lines(), not split("\n").
  • Immutability: trim(), replace() and friends return new strings.
  • Case: compare with equals(other, ignoreCase = true) or normalize both sides with lowercase(). Locale-sensitive cases (the Turkish dotless i) are rare, but lowercase() is locale-independent by design, which is what you want for data.
  • Parsing numbers: prefer toIntOrNull() and toDoubleOrNull() over toInt() plus a try.
  • Big files: readLines() loads everything; use useLines for large inputs, see Files and IO.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does "a,,c,".split(",") return?

    split keeps empty strings between and after delimiters, so the result has four elements: a, an empty string, c, and an empty string.
  2. 2. Why is lines() better than split("\n") for text of unknown origin?

    split on a bare newline leaves a stray \r at the end of each line in Windows text. lines() understands all three line endings.
  3. 3. How many windows does "abcdefg".windowed(3) produce?

    A window of 3 characters can start at positions 0 to 4 in a 7-character string, so there are 5 windows.
  4. 4. Why use split("=", limit = 2) when parsing greeting = hello = world?

    With limit = 2 the result has at most two parts: the key, and everything after the first delimiter.
  5. 5. Which call is the modern way to make the first letter of a string uppercase?

    capitalize() and toUpperCase() are deprecated. replaceFirstChar with uppercase() (or uppercaseChar()) is the current way.

Summary

  • split keeps empty strings; use a Regex such as \s+, filter, or substringBefore/substringAfter when that is not what you want. limit keeps the rest of the text together.
  • lines() and lineSequence() understand every line ending; combine with trimIndent() for multi-line literals.
  • trim, removePrefix, removeSuffix, ifBlank clean text; all return new strings.
  • windowed, chunked and zipWithNext look at neighbouring characters; groupingBy { }.eachCount() counts words in one step.
  • Parse small formats with split, toIntOrNull()/toDoubleOrNull() and associate, and report bad lines instead of crashing; use a real parser for quoted CSV.
  • Char functions (isDigit, digitToInt, uppercaseChar, arithmetic like 'a' + 2) cover character work; remember that one visible character can be several Chars.

Next: Files and IO