Skip to lesson

Parsing and cleaning text

Real-world text and tricky interview inputs rarely arrive clean: sentences have extra spaces, CSV rows have empty trailing columns, and user names mix punctuation with uppercase and lowercase letters. Knowing a handful of String and Character methods lets you normalise messy text in a few lines.

trim, strip, split, and simple regular expressions

Trim a sentence before splitting it, because leading spaces put an empty string at index 0 of the result. The code below also escapes the dot and keeps empty CSV columns.

Note that String.split(regex) takes a regular expression, not a literal delimiter string:

  • Splitting on one or more whitespace characters: s.trim().split("\\s+") treats any run of spaces, tabs, or newlines as a single separator. (Guard for trimmed.isEmpty() first, because "".split("\\s+") returns a 1-element array [""]!)
  • *Splitting on regex metacharacters (., |, +, `)**: In regex, . means "any character", so "192.168.1.1".split(".") returns an **empty array**! Escape it with "\\." (or Pattern.quote(".")`).
  • Keeping trailing empty columns in CSV (split(",", -1)): By default, "a,b,,".split(",") drops trailing empty strings and returns length 2 (["a", "b"]). Passing a negative limit line.split(",", -1) preserves every trailing empty column (["a", "b", "", ""]).

Example 1 · Splitting words with \\s+, escaping dots with \\., and preserving empty CSV columns

SplitTrapsDemo.javaJava
import java.util.Arrays;
public class SplitTrapsDemo {    public static void main(String[] args) {        String messy = "   Java   streams   and   strings  ";        String[] words = messy.trim().split("\\s+");        System.out.println("Words          : " + Arrays.toString(words));
        String ip = "192.168.0.1";        System.out.println("split('.')     : " + Arrays.toString(ip.split(".")) + " (WRONG: unescaped dot!)");        System.out.println("split('\\\\.')   : " + Arrays.toString(ip.split("\\.")));
        String csv = "Alice,95,,";        System.out.println("split(',')     : " + Arrays.toString(csv.split(",")) + " (drops trailing empties)");        System.out.println("split(',', -1) : " + Arrays.toString(csv.split(",", -1)) + " (keeps all 4 columns)");    }}
Output
Words          : [Java, streams, and, strings]
split('.')     : [] (WRONG: unescaped dot!)
split('\\.')   : [192, 168, 0, 1]
split(',')     : [Alice, 95] (drops trailing empties)
split(',', -1) : [Alice, 95, , ] (keeps all 4 columns)

What this code does

  • messy.trim().split("\\s+") strips outer spaces and collapses any internal multi-space gaps into clean word tokens.
  • In regex, . matches any character so ip.split(".") consumes everything and returns []; escaping as "\\." splits on literal dots. And csv.split(",", -1) preserves trailing empty CSV fields.

Before splitting a sentence into words, remove leading and trailing whitespace with s.trim() (or s.strip(), introduced in Java 11, which also removes Unicode whitespace). Why trim first? Because calling " hello world".split("\\s+") on a string with leading spaces puts an empty string "" at index 0 of the returned array!

  • s.trim().split("\\s+"): splits words separated by any number of spaces.
  • s.split("\\.") or s.split("\\|"): escapes regex special characters . and |.
  • line.split(",", -1): keeps trailing empty fields in a CSV line.

Character class methods for normalising messy text

The static methods on Character check letters, digits and case without hand-written ASCII ranges. The code below uses them to clean a user slug and a CSV record.

Example 2 · Real world: normalising a user slug and cleaning a CSV record

CleanUserInputDemo.javaJava
import java.util.Arrays;
public class CleanUserInputDemo {    // Converts "  Hello, World! 2026  " -> "hello-world-2026"    static String toUrlSlug(String title) {        StringBuilder sb = new StringBuilder();        boolean prevHyphen = false;        for (int i = 0; i < title.length(); i++) {            char c = title.charAt(i);            if (Character.isLetterOrDigit(c)) {                sb.append(Character.toLowerCase(c));                prevHyphen = false;            } else if (sb.length() > 0 && !prevHyphen) {                sb.append('-');                prevHyphen = true;            }        }        if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '-') {            sb.deleteCharAt(sb.length() - 1);        }        return sb.toString();    }
    static String[] cleanCsvRow(String line) {        String[] raw = line.split(",", -1);        for (int i = 0; i < raw.length; i++) {            raw[i] = raw[i].trim();        }        return raw;    }
    public static void main(String[] args) {        System.out.println("Slug    : " + toUrlSlug("  Hello, World! -- Java 17  "));        System.out.println("CSV row : " + Arrays.toString(cleanCsvRow("  ada@example.com ,  Ada Lovelace , , active ")));    }}
Output
Slug    : hello-world-java-17
CSV row : [ada@example.com, Ada Lovelace, , active]

What this code does

  • toUrlSlug uses Character.isLetterOrDigit and Character.toLowerCase to collapse any run of spaces and punctuation into a single hyphen '-'.
  • cleanCsvRow splits with limit = -1 so empty columns stay intact, then trims each cell.

When cleaning punctuation out of user input or checking alphanumeric palindromes like "A man, a plan, a canal: Panama", the static methods on java.lang.Character save you from writing error-prone ASCII range checks:

  • Character.isLetterOrDigit(c): true for letters and digits ('a'..'z', 'A'..'Z', '0'..'9', and Unicode letters/digits), false for spaces and punctuation.
  • Character.isLetter(c) and Character.isDigit(c): check only letters or only digits.
  • Character.isUpperCase(c) and Character.isLowerCase(c): check letter case.
  • Character.toLowerCase(c) and Character.toUpperCase(c): convert a single char without allocating a String.
  1. Loop over s with char c = s.charAt(i).
  2. Filter wanted characters using Character.isLetterOrDigit(c) or Character.isDigit(c).
  3. Normalise case on the fly with Character.toLowerCase(c).

Reversing the words in a sentence and cleaning CSV lines

A classic interview problem asks you to reverse the order of words in a messy string like " the sky is blue " to produce "blue is sky the" (single spaces between words, no leading or trailing spaces).

Example 3 · Reversing the words in a sentence without regex using a backward scan

ReverseWordsDemo.javaJava
public class ReverseWordsDemo {    static String reverseWords(String s) {        StringBuilder sb = new StringBuilder();        int i = s.length() - 1;        while (i >= 0) {            while (i >= 0 && s.charAt(i) == ' ') {                i--; // Skip spaces            }            if (i < 0) break;            int end = i;            while (i >= 0 && s.charAt(i) != ' ') {                i--; // Walk to the start of the word            }            if (sb.length() > 0) {                sb.append(' ');            }            sb.append(s, i + 1, end + 1); // Append s[i+1 .. end] directly!        }        return sb.toString();    }
    public static void main(String[] args) {        System.out.println("[" + reverseWords("  the   sky is  blue  ") + "]");        System.out.println("[" + reverseWords("hello") + "]");        System.out.println("[" + reverseWords("     ") + "]");    }}
Output
[blue is sky the]
[hello]
[]

What this code does

  • Scanning i from right to left finds the last word first ("blue"), then "is", "sky", and "the", skipping any number of leading, trailing, or middle spaces.
  • sb.append(s, i + 1, end + 1) appends the character range directly from s without allocating an intermediate substring object!

You can solve this in two ways:

  1. Split-and-join (O(n) time, O(n) space): Trim s, return "" if empty, split on "\\s+", and append words[i] backwards from words.length - 1 down to 0 into a StringBuilder.
  2. Two-index backward scan (O(n) time, O(n) output space without regex/array allocation): Scan i from s.length() - 1 down to 0, skip spaces, find the start of each word, and append s.substring(wordStart, wordEnd) to a StringBuilder. In real-world backend code, the same trimming and character-filtering rules clean user-submitted emails, phone numbers, and CSV rows before saving them to a database.
Always check if (trimmed.isEmpty()) return ""; before calling trimmed.split("\\s+"), because in Java "".split("\\s+") returns new String[]{""} (length 1) rather than an empty array!

Next step

Check your understanding

10 quick questions