Parsing and cleaning text
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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 fortrimmed.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"\\."(orPattern.quote(".")`). - Keeping trailing empty columns in CSV (
split(",", -1)): By default,"a,b,,".split(",")drops trailing empty strings and returns length2(["a", "b"]). Passing a negative limitline.split(",", -1)preserves every trailing empty column (["a", "b", "", ""]).
Example 1 · Splitting words with \\s+, escaping dots with \\., and preserving empty CSV columns
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)"); }}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 soip.split(".")consumes everything and returns[]; escaping as"\\."splits on literal dots. Andcsv.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("\\.")ors.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
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 "))); }}Slug : hello-world-java-17 CSV row : [ada@example.com, Ada Lovelace, , active]
What this code does
toUrlSlugusesCharacter.isLetterOrDigitandCharacter.toLowerCaseto collapse any run of spaces and punctuation into a single hyphen'-'.cleanCsvRowsplits withlimit = -1so 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):truefor letters and digits ('a'..'z','A'..'Z','0'..'9', and Unicode letters/digits),falsefor spaces and punctuation.Character.isLetter(c)andCharacter.isDigit(c): check only letters or only digits.Character.isUpperCase(c)andCharacter.isLowerCase(c): check letter case.Character.toLowerCase(c)andCharacter.toUpperCase(c): convert a singlecharwithout allocating aString.
- Loop over
swithchar c = s.charAt(i). - Filter wanted characters using
Character.isLetterOrDigit(c)orCharacter.isDigit(c). - 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
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(" ") + "]"); }}[blue is sky the] [hello] []
What this code does
- Scanning
ifrom 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 fromswithout allocating an intermediatesubstringobject!
You can solve this in two ways:
- Split-and-join (O(n) time, O(n) space): Trim
s, return""if empty, split on"\\s+", and appendwords[i]backwards fromwords.length - 1down to0into aStringBuilder. - Two-index backward scan (O(n) time, O(n) output space without regex/array allocation): Scan
ifroms.length() - 1down to0, skip spaces, find the start of each word, and appends.substring(wordStart, wordEnd)to aStringBuilder. 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.
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