The simplest way to split a string in Java is to call the split() method on the string object, passing the delimiter as a regular expression: str.split(delimiter). For example, "apple,banana,cherry".split(",") returns the array {"apple", "banana", "cherry"}. This method is part of the String class and works in all Java versions.
Background: Why Splitting Strings Matters
Splitting strings is one of the most common operations in programming, used to parse CSV files, extract tokens from user input, process log lines, or break down URLs. Java has evolved its string-handling capabilities over the years: the original StringTokenizer class (from Java 1.0) was the only option until Java 1.4 introduced the split() method, which uses regular expressions. Later, Java 8 added String.join() for the reverse operation, and Java 11 introduced String.lines() to split on line terminators. Understanding split() is essential because it is the most flexible and widely used approach today.
How split() Works Under the Hood
The split() method takes a regular expression (regex) as its delimiter and internally compiles it into a Pattern object. It then uses that pattern to find matches and divides the string around them. The method returns a String[] array. There are two overloads:
split(String regex)– splits on every occurrence of the regex.split(String regex, int limit)– controls how many times the pattern is applied.
The limit parameter changes behavior: if positive, the pattern is applied at most limit-1 times, and the last element contains the remainder; if zero, trailing empty strings are removed; if negative, trailing empty strings are kept. For example:
String s = "a,b,";
s.split(",") // returns {"a", "b"} (trailing empty removed)
s.split(",", -1) // returns {"a", "b", ""} (kept)
s.split(",", 2) // returns {"a", "b,"}
Internally, split() calls Pattern.compile(regex).split(this, limit). This means the regex is compiled each time you call split(), which can be a performance concern if you split many strings with the same delimiter. In that case, precompile the pattern using Pattern.compile() and reuse it.
Choosing the Right Delimiter and Regex
The delimiter is always a regular expression, not a plain literal string. This is a common source of confusion. For example, to split on a dot (.), you must escape it as "\\." because a dot matches any character. Similarly, to split on a backslash, you need "\\\\". Here are common delimiters:
- Comma:
"," - Whitespace (one or more spaces, tabs, newlines):
"\\s+" - Pipe symbol:
"\\|"(pipe is an alternation operator) - Hyphen:
"-"(no escape needed) - Multiple possible delimiters:
"[,;]"(comma or semicolon)
If you want to split on a literal string that contains regex metacharacters (like ., *, ?), you can use Pattern.quote() to escape it automatically: str.split(Pattern.quote(".")).
Common Problems and Pitfalls
One frequent issue is that split() removes trailing empty strings by default. If you need to preserve them, use the negative limit as shown above. Another pitfall is that the regex "" (empty string) splits the string into individual characters (each character as a separate element), which might be unexpected. Also, be careful with leading delimiters: ",a,b".split(",") returns an array with an empty first element because the string starts with the delimiter. To ignore leading empty strings, you can strip them first or use a regex that matches the delimiter at the start, like "^,|," but that gets complex. A simpler approach is to check if the string starts with the delimiter and handle it manually.
Alternatives to split()
While split() is the go-to, there are alternatives depending on the use case:
- StringTokenizer – legacy class, does not support regex, but is faster for simple delimiters. It is not recommended for new code because it is outdated and its behavior with empty tokens is inconsistent.
- Scanner – useful for reading tokens from a stream, e.g.,
new Scanner(str).useDelimiter(","). - Pattern.splitAsStream() – Java 8+, returns a
Stream<String>which is convenient for functional pipelines. - String.lines() – Java 11+, splits on line terminators and returns a stream of lines.
For very large strings, consider using Pattern.splitAsStream() to avoid materializing the whole array at once, though the difference is usually negligible.
Performance Considerations and Best Practices
If you split a string once, performance is irrelevant. But if you split millions of times in a loop, the overhead of compiling the regex each time adds up. Precompile the pattern:
Pattern p = Pattern.compile(",");
for (String line : lines) {
String[] parts = p.split(line);
// process parts
}
Also, consider using indexOf() and substring() for very simple delimiters if you need extreme speed, but that is rarely necessary. The split() method is well-optimized and fine for most applications.
Frequently Asked Questions
How do I split a string by newline?
Use str.split("\\n") for a literal newline, or better, str.split("\\r?\\n") to handle both Windows and Unix line endings. In Java 11+, you can use str.lines() which automatically handles all line terminators.
Why does my split return an empty first element?
If the string starts with the delimiter, the first element will be an empty string. For example, ",a".split(",") returns {"", "a"}. To remove leading empty strings, you can strip the leading delimiter first or use a regex that matches the delimiter at the start, but the simplest is to check and remove it before splitting.
Can I split a string into a List instead of an array?
Yes, convert the array to a list: Arrays.asList(str.split(",")). Or in Java 8+, use Stream.of(str.split(",")).collect(Collectors.toList()). For more control, use Pattern.splitAsStream() and collect.
What is the difference between split and StringTokenizer?
split() uses regular expressions, while StringTokenizer treats delimiters as literal characters. StringTokenizer is older and does not support regex, but it is slightly faster for simple delimiters. However, StringTokenizer does not handle empty tokens consistently and is not recommended for new code.
How do I split a string by multiple delimiters like comma and semicolon?
Use a character class in the regex: str.split("[,;]") splits on either a comma or a semicolon. For more complex patterns, you can use alternation: str.split(",|;").
Why does split not work with a dot?
Because a dot in regex matches any character. You need to escape it: str.split("\\.") or use Pattern.quote(".").
Related
- Shortcut to Select Cell Range in Excel
- Shortcut to Switch Between Windows (All OS)
- Generate Random Number HTML: JS & Math.random Code
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Make Every Other Row a Color in Excel (2 Ways)To color every other row in Excel, format your data as a table and choose a banded style,…
- How to Hide Cells in Excel Without Deleting DataTo hide cells in Excel, select the rows or columns containing them, then choose Home > Cells >…
- CAF Data Validation Tracker in Google SheetsGoogle Sheets does not have a built-in product called a “CAF data validation tracker,” and CAF can mean…
- Excel: Copy an Entire Worksheet to a New Workbook SafelyTo copy an entire worksheet into a new workbook in Excel for Microsoft 365 on Windows, right-click the…
- Excel: How to Consolidate Multiple Rows Into One CellIf your goal is to combine values from matching rows into one cell, put the matching key in…
- Styles in Word: How They Work and How to Use Them WellStyles in Microsoft Word are named sets of formatting that you can apply to text, paragraphs, tables, or…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.