In Java, you split a string using the String.split(String regex) method, which returns an array of substrings separated by a regular expression. For example, "a,b,c".split(",") returns ["a", "b", "c"]. This method is part of the java.lang.String class and works in all Java versions from 1.4 onward.
How String.split() Works
The split() method takes a regular expression (regex) as its argument and divides the string wherever that pattern matches. The method has two overloads:
split(String regex)– splits on every match, discarding trailing empty strings.split(String regex, int limit)– controls how many times the split is applied and whether trailing empty strings are kept.
The regex is compiled internally using Pattern.compile(), so any valid Java regex pattern works. Common delimiters include commas, spaces, pipes, and newlines. For example, "one two three".split(" ") gives ["one", "two", "three"].
Using the Limit Parameter
The second overload, split(regex, limit), gives you control over the result array size. The behavior depends on the limit value:
- Positive limit (e.g.,
2): The pattern is applied at mostlimit-1times, and the last element contains the remainder of the string. Example:"a,b,c".split(",", 2)returns["a", "b,c"]. - Zero limit: The default behavior – trailing empty strings are removed. Example:
"a,b,".split(",")returns["a", "b"]. - Negative limit (e.g.,
-1): The pattern is applied as many times as possible, and trailing empty strings are kept. Example:"a,b,".split(",", -1)returns["a", "b", ""].
This is crucial when parsing CSV-like data where empty fields matter. Many developers are surprised that "a,b,".split(",") drops the last empty string, leading to off-by-one errors.
Escaping Special Characters
Because split() takes a regex, characters like dot (.), pipe (|), asterisk (*), and backslash (\) must be escaped. For instance, splitting on a literal dot requires "a.b.c".split("\\.") – not split("."), which would match any character and return an empty array for most strings. Similarly, to split on a pipe, use "a|b".split("\\|") or split(Pattern.quote("|")).
A common mistake is forgetting to escape the backslash itself. In Java source code, a single backslash is written as "\\" (two characters). For example, to split on a backslash, use "a\\b".split("\\\\") – yes, four backslashes in the source.
Alternative: StringTokenizer
Before Java 1.4, the typical way to split was using java.util.StringTokenizer. This class is still available but is considered legacy and not recommended for new code. Unlike split(), StringTokenizer does not support regex; it treats delimiters as single characters or a set of characters. For example:
StringTokenizer st = new StringTokenizer("a,b,c", ",");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
It also does not return empty tokens. For instance, "a,,c" would yield only "a" and "c", skipping the empty middle. If you need empty strings, use split() with a negative limit.
Performance and Memory Considerations
For most use cases, split() is fast enough. However, if you are splitting a very large string or doing it millions of times in a loop, consider that each call compiles the regex pattern anew. You can precompile the pattern using Pattern.compile() and then call pattern.split(input) to reuse it:
Pattern comma = Pattern.compile(",");
String[] parts = comma.split("a,b,c");
This avoids recompiling the regex on every call. Also, the returned array and the resulting substrings are new objects, so memory usage can spike if you hold onto many split results. If memory is a concern and you only need to iterate, consider using a Scanner with a delimiter, or a manual loop with indexOf() and substring().
Handling Whitespace and Multiple Delimiters
Often you want to split on any whitespace (spaces, tabs, newlines). The regex "\\s+" matches one or more whitespace characters. Example: " hello world ".split("\\s+") returns ["hello", "world"] – note that leading whitespace creates an empty first element if the string starts with spaces. To avoid that, trim the string first or use a regex that ignores leading delimiters.
For multiple different delimiters, use a character class. For instance, to split on commas, semicolons, or pipes: "a;b,c|d".split("[,;|]") returns ["a", "b", "c", "d"]. This is more efficient than chaining multiple split() calls.
Common Pitfalls and Misconceptions
One frequent misconception is that split() modifies the original string – it does not; strings are immutable, so it returns a new array of new strings. Another is that the regex is matched literally; always remember it’s a regex. Also, be aware that split() with a zero limit removes trailing empty strings, which can cause data loss. If you need to preserve all fields, use a negative limit.
Another pitfall is using split() on an empty string. "".split(",") returns an array of length 1 containing an empty string, not an empty array. This is often surprising. To get an empty array, check if (str.isEmpty()) before splitting.
Frequently Asked Questions
How do I split a string by newline?
Use str.split("\\n") for a literal newline, or str.split("\\r?\\n") to handle Windows (\r\n) and Unix (\n) line endings. If the string ends with a newline, trailing empty strings are removed by default; use split("\\r?\\n", -1) to keep them.
What is the difference between split() and StringTokenizer?
split() uses regex and can handle complex patterns, returns an array, and can include empty strings with a negative limit. StringTokenizer is older, uses literal character delimiters, never returns empty tokens, and is less flexible. For new code, use split().
How do I split a string into individual characters?
Use str.split("") – this splits on every zero-width position, but it includes a leading empty string in some Java versions. Better: use str.toCharArray() to get a char[], or str.codePoints() for Unicode code points.
Why does split(“.”) return an empty array?
Because . in regex matches any character, so the string is split at every position, and since the limit is zero, trailing empty strings are removed – leaving nothing. Escape it as "\\." to split on a literal dot.
Can I split a string and keep the delimiters?
No, split() discards the delimiters. To keep them, use a regex with lookahead or lookbehind, e.g., str.split("(?<=\\,)") splits after each comma but keeps the comma in the previous part. Alternatively, use Pattern with Matcher.find() to capture both.
Is there a way to split without regex?
If you only need to split on a single literal character, you can use a loop with indexOf() and substring(), or use StringTokenizer. For a literal string (multiple characters), you can use str.split(Pattern.quote("delimiter")) to treat it as literal.
Related
- Data Entry in Computerized Method: How It Works
- Split Method in String: How It Works
- Aa to AZ Column Number: Excel Column Letters Explained
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Can You Type Subscript in Excel? Methods and LimitsYes, you can type subscript in Excel. In the Microsoft 365 desktop app for Windows, select the characters…
- Excel Group Rows Shortcut: The Key and How It WorksIn Excel for Microsoft 365 on Windows, select the rows you want to group and press Alt+Shift+Right Arrow.…
- Excel NOT ISBLANK: How to Check for Nonblank CellsTo check whether a cell is not blank in Excel, use =NOT(ISBLANK(A2)), replacing A2 with the cell you…
- How to Hide Columns in Excel: A Step-by-Step GuideTo hide columns in Excel for Microsoft 365 on Windows, select one or more column headers, right-click the…
- Google Sheets Data Validation Dropdown: Setup and TipsTo create a Google Sheets data validation dropdown, select the cells, choose Data > Data validation > Add…
- Best Way to Make a Budget Sheet in Google Sheets: A GuideThe best way to make a budget sheet in Google Sheets is to keep a transaction log and…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.