Use the appropriately named method String#split().

String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

Note that split's argument is assumed to be a regular expression, so remember to escape special characters if necessary.

there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".

For instance, to split on a period/dot . (which means "any character" in regex), use either backslash \ to escape the individual special character like so split("\\."), or use character class [] to represent literal character(s) like so split("[.]"), or use Pattern#quote() to escape the entire string like so split(Pattern.quote(".")).

String[] parts = string.split(Pattern.quote(".")); // Split on the exact string.

To test beforehand if the string contains certain character(s), just use String#contains().

if (string.contains("-")) {
    // Split it.
} else {
    throw new IllegalArgumentException("String " + string + " does not contain -");
}

Note, this does not take a regular expression. For that, use String#matches() instead.

If you'd like to retain the split character in the resulting parts, then make use of positive lookaround. In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing ?<= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556

In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing ?= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556

If you'd like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of split() method.

String string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42
Answer from BalusC on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ ref_string_split.asp
Java String split() Method
The split() method splits a string into an array of substrings using a regular expression as the separator. If a limit is specified, the returned array will not be longer than the limit.
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 8 โ€บ docs โ€บ api โ€บ java โ€บ lang โ€บ String.html
String (Java Platform SE 8 )
October 20, 2025 - the array of strings computed by splitting this string around matches of the given regular expression ... Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter. ... String message = String.join("-", "Java", "is", "cool"); ...
Discussions

How do I split a string in Java? - Stack Overflow
I want to split a string using a delimiter, for example split "004-034556" into two separate strings by the delimiter "-": part1 = "004"; part2 = "034556"; ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Splitting strings based on a delimiter - Stack Overflow
I am trying to break apart a very simple collection of strings that come in the forms of 0|0 10|15 30|55 etc etc. Essentially numbers that are seperated by pipes. When I use java's string split More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - How to split a String by space - Stack Overflow
if somehow you don't wanna use String split method then you can use StringTokenizer class in Java as.. More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - How to split a string with any whitespace chars as delimiters - Stack Overflow
9 How do I make Java ignore the number of spaces in a string when splitting? More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ split-string-java-examples
Java String split() Method - GeeksforGeeks
December 20, 2025 - split() method in Java is used to divide a string into an array of substrings based on a specified delimiter or regular expression.
๐ŸŒ
Xperti
xperti.io โ€บ home โ€บ split() string method in java with example
Split() String Method in Java: A guide to Split Strings in Java
September 13, 2023 - Java string split() method allows the user to split a string into one or more substrings based on a specific Java string delimiter or a regular expression. The delimiter can be any character but the most commonly used characters are comma(,) ...
๐ŸŒ
Decodejava
decodejava.com โ€บ java-string-split.htm
Java String split() Method - Decodejava.com
In the last code, we have split the value in a String object into parts using delimiter value of space \s. An extra \ may be required on some specific Operating System, hence we have used \\s. ... // Java - Calling the split() method of String, with predefined number of parts class StringSplit3 { public static void main(String[] ar) { String str1= new String("This is a String split example"); System.out.println("Original string is : "+ str1); //Splitting the value in a String object with a different delimiter value of space String strArr[]=str1.split(" ", 2); // We are asking for 2 partitions of String.
Top answer
1 of 16
3415

Use the appropriately named method String#split().

String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

Note that split's argument is assumed to be a regular expression, so remember to escape special characters if necessary.

there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".

For instance, to split on a period/dot . (which means "any character" in regex), use either backslash \ to escape the individual special character like so split("\\."), or use character class [] to represent literal character(s) like so split("[.]"), or use Pattern#quote() to escape the entire string like so split(Pattern.quote(".")).

String[] parts = string.split(Pattern.quote(".")); // Split on the exact string.

To test beforehand if the string contains certain character(s), just use String#contains().

if (string.contains("-")) {
    // Split it.
} else {
    throw new IllegalArgumentException("String " + string + " does not contain -");
}

Note, this does not take a regular expression. For that, use String#matches() instead.

If you'd like to retain the split character in the resulting parts, then make use of positive lookaround. In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing ?<= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556

In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing ?= group on the pattern.

String string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556

If you'd like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of split() method.

String string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42
2 of 16
91

An alternative to processing the string directly would be to use a regular expression with capturing groups. This has the advantage that it makes it straightforward to imply more sophisticated constraints on the input. For example, the following splits the string into two parts, and ensures that both consist only of digits:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

class SplitExample
{
    private static Pattern twopart = Pattern.compile("(\\d+)-(\\d+)");

    public static void checkString(String s)
    {
        Matcher m = twopart.matcher(s);
        if (m.matches()) {
            System.out.println(s + " matches; first part is " + m.group(1) +
                               ", second part is " + m.group(2) + ".");
        } else {
            System.out.println(s + " does not match.");
        }
    }

    public static void main(String[] args) {
        checkString("123-4567");
        checkString("foo-bar");
        checkString("123-");
        checkString("-4567");
        checkString("123-4567-890");
    }
}

As the pattern is fixed in this instance, it can be compiled in advance and stored as a static member (initialised at class load time in the example). The regular expression is:

(\d+)-(\d+)

The parentheses denote the capturing groups; the string that matched that part of the regexp can be accessed by the Match.group() method, as shown. The \d matches and single decimal digit, and the + means "match one or more of the previous expression). The - has no special meaning, so just matches that character in the input. Note that you need to double-escape the backslashes when writing this as a Java string. Some other examples:

([A-Z]+)-([A-Z]+)          // Each part consists of only capital letters 
([^-]+)-([^-]+)            // Each part consists of characters other than -
([A-Z]{2})-(\d+)           // The first part is exactly two capital letters,
                           // the second consists of digits
Find elsewhere
๐ŸŒ
Briebug Blog
blog.briebug.com โ€บ blog โ€บ java-split-string
Using the Java String.split() Method
The Java String.split() method has two variations, commonly known as method overloading, which are both used to split a String into an array of Strings, using a passed delimiter or regular expression.
๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ javas-pattern-splitasstream-method-explained-99ca4b345ccd
Javaโ€™s Pattern.splitAsStream() Method Explained | Medium
October 29, 2024 - The split() method returns an array of strings (String[]), which means it immediately splits the input string into an array, storing all the elements in memory. This approach works well for small strings or when you need to access all the parts ...
๐ŸŒ
Java Guides
javaguides.net โ€บ 2024 โ€บ 06 โ€บ java-string-split-method.html
Java String split() Method
June 10, 2024 - The String.split() method in Java is used to split a string into an array of substrings based on a specified delimiter.
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ java โ€บ how to split a string in java
How to split a string in Java | Sentry
public class Main { public static void main(String[] arg) { String str = "how:to:split:a:string:in:java"; String[] arrOfStr = str.split(":"); for (String a : arrOfStr) { System.out.println(a); } } }
Top answer
1 of 16
835

What you have should work. If, however, the spaces provided are defaulting to... something else? You can use the whitespace regex:

str = "Hello I'm your String";
String[] splited = str.split("\\s+");

This will cause any number of consecutive spaces to split your string into tokens.

2 of 16
149

While the accepted answer is good, be aware that you will end up with a leading empty string if your input string starts with a white space. For example, with:

String str = " Hello I'm your String";
String[] splitStr = str.split("\\s+");

The result will be:

splitStr[0] == "";
splitStr[1] == "Hello";
splitStr[2] == "I'm";
splitStr[3] == "Your";
splitStr[4] == "String";

So you might want to trim your string before splitting it:

String str = " Hello I'm your String";
String[] splitStr = str.trim().split("\\s+");

[edit]

In addition to the trim caveat, you might want to consider the unicode non-breaking space character (U+00A0). This character prints just like a regular space in string, and often lurks in copy-pasted text from rich text editors or web pages. They are not handled by .trim() which tests for characters to remove using c <= ' '; \s will not catch them either.

Instead, you can use \p{Blank} but you need to enable unicode character support as well which the regular split won't do. For example, this will work: Pattern.compile("\\p{Blank}", UNICODE_CHARACTER_CLASS).split(words) but it won't do the trim part.

The following demonstrates the problem and provides a solution. It is far from optimal to rely on regex for this, but now that Java has 8bit / 16bit byte representation, an efficient solution for this becomes quite long.

public class SplitStringTest {
    static final Pattern TRIM_UNICODE_PATTERN = Pattern.compile("^\\p{Blank}*(.*)\\p{Blank}*$", UNICODE_CHARACTER_CLASS);
    static final Pattern SPLIT_SPACE_UNICODE_PATTERN = Pattern.compile("\\p{Blank}+", UNICODE_CHARACTER_CLASS);

    public static String[] trimSplitUnicodeBySpace(String str) {
        Matcher trimMatcher = TRIM_UNICODE_PATTERN.matcher(str);
        boolean ignored = trimMatcher.matches();
        return SPLIT_SPACE_UNICODE_PATTERN.split(trimMatcher.group(1));
    }

    @Test
    public void test() {
        String words = " Hello    I'm\u00A0your String\u00A0";
        // non-breaking space here --^ and there -----^

        String[] split = words.split(" ");
        String[] trimAndSplit = words.trim().split(" ");
        String[] splitUnicode = SPLIT_SPACE_UNICODE_PATTERN.split(words);
        String[] trimAndSplitUnicode = trimSplitUnicodeBySpace(words);

        System.out.println("words: [" + words + "]");
        System.out.println("split: [" + String.join("][", split) + "]");
        System.out.println("trimAndSplit: [" + String.join("][", trimAndSplit) + "]");
        System.out.println("splitUnicode: [" + String.join("][", splitUnicode) + "]");
        System.out.println("trimAndSplitUnicode: [" + String.join("][", trimAndSplitUnicode) + "]");
    }
}

Results in:

words: [ Hello    I'm your String ]
split: [][Hello][][][][I'm your][String ]
trimAndSplit: [Hello][][][][I'm your][String ]
splitUnicode: [][Hello][I'm][your][String]
trimAndSplitUnicode: [Hello][I'm][your][String]
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java string โ€บ java string.split()
Java.String.split() | Baeldung
March 13, 2025 - This method returns an array of strings. Each element in the array is a substring from the original string. The regex is the regular expression that defines the delimiter. We can also pass a limit on the number of splits to the split() method.
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 560479 โ€บ java โ€บ Split-string-word-character
Split string on a word not just a character (Java in General forum at Coderanch)
December 1, 2011 - Regexes are good, but they're not ... pattern (and will probably lead to more mistakes). What about this: 1. Use String.split("\\s+") to split the string into whitespace-delimited "words"....
๐ŸŒ
Software Testing Help
softwaretestinghelp.com โ€บ home โ€บ java โ€บ java string split() method โ€“ how to split a string in java
Java String Split() Method โ€“ How To Split A String In Java
April 1, 2025 - Using the Java Split() method, we will successfully print each of the words without including the space. Explanation: Here, we have initialized a Java String variable and using the regular expression โ€œ\\sโ€, we have split the String wherever whitespace occurred.
๐ŸŒ
How to do in Java
howtodoinjava.com โ€บ home โ€บ string โ€บ different ways to split a string in java
Different Ways to Split a String in Java
January 8, 2023 - The String.split() method is the best and recommended way to split the strings. The tokens are returned in form of a string array that frees us to use it as we wish. The following Java program splits a string with the delimiter comma.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java string โ€บ split a string in java
Split a String in Java | Baeldung
January 8, 2024 - Let us look at some examples. Weโ€™ll start with splitting by a comma: String[] splitted = "peter,james,thomas".split(",");
๐ŸŒ
IONOS
ionos.com โ€บ digital guide โ€บ websites โ€บ web development โ€บ string splitting in java
How to split strings in Java - IONOS
January 6, 2025 - In this example, a string variable x is initialized. Then Javaโ€™s split() is used on the string. The parameter searches the string for spaces and splits it in the places where it finds them. The result is then saved in an array called โ€œoutputโ€. The for loop is used to list the substrings.