How to Split a String in Java: A Complete Guide for Beginners and Pros

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

"Help, I can't split a string!" — The story of one problem

\n\n

Imagine: you are writing a log parser in Java, processing a CSV file, or just want to split user input into words. And then — stop. How do you do it? If you've ever Googled "How do I split a string in Java", you know: this question on Stack Overflow has gathered hundreds of thousands of views. Not because Java programmers are lazy, but because split() is a powerful thing, but with pitfalls.

\n\n

In this article, we will cover splitting strings in Java from A to Z. You will learn how the split() method works, what surprises regular expressions have in store, and how to avoid the rake that awaits every second beginner. Let's go!

\n\n

The split() method: your main tool

\n\n

The String class in Java offers two overloaded variants of the split() method:

\n\n
public String[] split(String regex)\npublic String[] split(String regex, int limit)
\n\n

The first variant takes a regular expression and returns an array of strings. The second does the same, but with a limit on the number of parts. Sounds simple? Let's look at examples.

\n\n

Basic example: splitting by space

\n\n
public class SplitExample {\n    public static void main(String[] args) {\n        String text = "Java splits strings easily";\n        String[] words = text.split(" ");\n        \n        for (String word : words) {\n            System.out.println(word);\n        }\n    }\n}
\n\n

Output:

\n
Java\nsplits\nstrings\neasily
\n\n

Works? It works. But what if you have multiple consecutive spaces? Then empty strings will end up in the array. Unpleasant, right?

\n\n

Splitting a string in Java by comma (CSV)

\n\n

One of the most common tasks is splitting a string in Java by comma. Let's say you have a CSV string:

\n\n
String csv = "apple,pear,banana,orange";\nString[] fruits = csv.split(",");\n\nfor (String fruit : fruits) {\n    System.out.println(fruit.trim()); // trim() removes extra spaces\n}
\n\n

Output:

\n
apple\npear\nbanana\norange
\n\n

Note: we added trim() because in real data, spaces often follow commas. Without this, you will get " apple" with a leading space — and then you'll wonder why the strings don't match.

\n\n

Regular expressions: magic and pain

\n\n

The split() method accepts a regular expression. This gives enormous flexibility but requires caution. Let's look at popular scenarios.

\n\n

Splitting by dot

\n\n

Want to split an IP address "192.168.1.1"? The naive code str.split(".") won't work. Why? Because the dot in regular expressions is a special character meaning "any character". As a result, you will get an array of empty strings.

\n\n

The correct solution is to escape the dot:

\n\n
String ip = "192.168.1.1";\nString[] parts = ip.split("\\\\."); // Double backslash!\n\nfor (String part : parts) {\n    System.out.println(part);\n}\n// Output: 192 168 1 1
\n\n

Remember: in Java, to escape in regex, you use a double backslash \\\\. A single \\ is an escape character for the string, while a double is for the regex.

\n\n

Splitting by multiple delimiters

\n\n

What to do if the string contains commas, semicolons, and spaces? Use a character class in square brackets:

\n\n
String messy = "apple;pear,banana orange";\nString[] items = messy.split("[;,\\\\s]+"); // ; or , or whitespace characters\n\nfor (String item : items) {\n    System.out.println(item);\n}\n// Output: apple pear banana orange
\n\n

The + sign means "one or more" — this ensures that a sequence of delimiters does not

Blogs

Book Recommendations