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
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-split-a-string-by-character
Java - Split a String by Character - GeeksforGeeks
July 23, 2025 - In Java, we can use the split() method from the String class to split a string by character, which simplifies this process by taking a regular expression (regex) as its argument.
Top answer
1 of 16
3416

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
Discussions

algorithm - Split string by character in Java - Code Review Stack Exchange
I have this code, which goes through a string and split it using a char delimiter. I am concerned where it can be improved. Main concerns are speed and memory usage with speed as the priority. Any... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
March 18, 2017
java - Split string into array of character strings - Stack Overflow
I need to split a String into an array of single character Strings. Eg, splitting "cat" would give the array "c", "a", "t" ... As a quick reference, "".join(["c","a","t"]) to get "cat" back. ... Java 8: .split("") will do it. More on stackoverflow.com
🌐 stackoverflow.com
Split String every nth char / or the first occurrence of a period
If you want to split only on full sentences, just check for the location of the next full stop. If the phrase length is less than 15 characters, search for the subsequent full stop, check the length of both is still less than 15, and add it to the phrase. Repeat until the phrase is longer than 15 characters. More on reddit.com
🌐 r/java
8
0
August 28, 2013
Split a string with multiple delimiters

Erm, you can just put all of the delimiters you want in the quotes for the string passed to .split()

[PS] C:\Users\> $string = "part1.part2;part3"
[PS] C:\Users\> $string.split(".;")
part1
part2
part3
More on reddit.com
🌐 r/PowerShell
7
19
October 14, 2014
🌐
Medium
medium.com › @AlexanderObregon › javas-string-split-method-explained-77bdaddaae79
Java’s String split() Method Explained
June 25, 2024 - In this example, the string "Hello world from Java" is split into an array of substrings using the space " " as the delimiter. The output will be: ... The split() method can also handle more complex delimiters by using regular expressions.
🌐
Interview Kickstart
interviewkickstart.com › home › blogs › learn › java string split() method: syntax, delimiters, and examples
Understanding Java String Split() Method | Interview Kickstart
April 1, 2026 - A character set is defined by wrapping the desired delimiters in square brackets [ ]. A regex character set like [,;|] tells the Java split() method to treat each character inside the brackets as an individual valid delimiter.
🌐
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 - Answer: Java String Split() decomposes or splits the invoking string into parts where each part is delimited by the BRE (Basic Regular Expression) that we pass in the regEx.
🌐
TutorialKart
tutorialkart.com › java › how-to-split-a-string-with-specific-character-as-delimiter-in-java
How to Split a String with Specific Character as Delimiter in Java?
January 13, 2021 - In the following program, we have ... Java Tutorial, we learned how to split a string by specific character, using String.split() method....
🌐
Baeldung
baeldung.com › home › java › java string › java string.split()
Java.String.split() | Baeldung
November 9, 2017 - In this article, we explored the String.split() method, which allows us to divide strings into smaller substrings based on specified delimiters. We learned how to use this method with regular expressions, handle different character encodings, ...
Find elsewhere
🌐
Mkyong
mkyong.com › home › java › how to split a string in java
How to split a string in Java - Mkyong.com
February 9, 2022 - str.split("\\|") // backslash \ to escape regex special character str.split("[|]") // character class [] to escape regex special character str.split(Pattern.quote("|")) // Pattern#quote() to escape regex special character · The below example tries to split a string by a unescape pipe symbol |. ... package com.mkyong.string.split; public class StringSplitSpecial { public static void main(String[] args) { String csv = "a|b|c|d"; String[] output = csv.split("|"); for (String s : output) { System.out.println(s); } } } ... The below example tries to split a string by an escaped pipe symbol |. ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › split-string-java-examples
Java String split() Method - GeeksforGeeks
May 13, 2026 - The split() method in Java is used to divide a string into multiple parts based on a specified delimiter (regular expression). It returns an array of substrings after splitting the original string.
Top answer
1 of 3
6

Sloppiness

There are several careless mistakes that are easy to fix.

Don't use implementation types in declaration, unless you really need to use a specific feature of that implementation:

ArrayList<String> arr = new ArrayList<String>();

Use the interface type instead:

List<String> arr = new ArrayList<String>();

Instead of creating a new StringBuilder, it might be faster to reset it, like this:

sb.setLength(0);

See this discussion for more details.


Don't convert a List to an array like this:

return arr.toArray(new String[0]);

It's recommended to pass a correctly sized array:

return arr.toArray(new String[arr.size()]);

Better unit tests

Give your test cases meaningful names. So that when your IDE reports some of them failing, it will be easier to understand what failed. For example:

@Test
public void testNormalSentence() {
    final String str1 = "Because";
    final String str2 = "I'm";
    final String str3 = "Batman";
    final char delim = ' ';
    String[] parts = StringUtility.split(str1 + delim + str2 + delim + str3, delim);
    Assert.assertEquals(Arrays.asList(str1, str2, str3), Arrays.asList(parts));
}

@Test
public void testStartingWithDelim() {
    final String str1 = "";
    final String str2 = "I'm";
    final String str3 = "Batman";
    final char delim = ' ';
    String[] parts = StringUtility.split(str1 + delim + str2 + delim + str3, delim);
    Assert.assertEquals(Arrays.asList(str1, str2, str3), Arrays.asList(parts));
}

@Test
public void testEmptyString() {
    final String str1 = "";
    final char delim = ' ';
    String[] parts = StringUtility.split(str1, delim);
    Assert.assertEquals(Arrays.asList(str1), Arrays.asList(parts));
}

These new names describe well exactly what they are testing. This should help understanding the code.


The assertions can be simplified, instead of:

String[] parts = StringUtility.split(str1 + delim + str2 + delim + str3, delim);
Assert.assertTrue(parts.length == 3);
Assert.assertTrue(parts[0].equals(str1));
Assert.assertTrue(parts[1].equals(str2));
Assert.assertTrue(parts[2].equals(str3));

You could simplify like this:

String[] parts = StringUtility.split(str1 + delim + str2 + delim + str3, delim);
Assert.assertEquals(Arrays.asList(str1, str2, str3), Arrays.asList(parts));

This is exactly the same, but shorter, and a lot easier to write.


I would add some more test cases:

@Test
public void testOnlyDelim() {
    final String str1 = "";
    final char delim = ' ';
    String[] parts = StringUtility.split("" + delim + delim, delim);
    Assert.assertEquals(Arrays.asList(str1, str1, str1), Arrays.asList(parts));
}

@Test
public void testNotContainingDelim() {
    final String str1 = "hello";
    final char delim = 'x';
    String[] parts = StringUtility.split(str1, delim);
    Assert.assertEquals(Arrays.asList(str1), Arrays.asList(parts));
}

Suggested implementation

@heslacher's implementation is very close to my taste. Here's a variation of that, with some minor changes:

public static String[] split(String strToSplit, char delimiter) {
    List<String> arr = new ArrayList<>();
    int foundPosition;
    int startIndex = 0;
    while ((foundPosition = strToSplit.indexOf(delimiter, startIndex)) > -1) {
        arr.add(strToSplit.substring(startIndex, foundPosition));
        startIndex = foundPosition + 1;
    }
    arr.add(strToSplit.substring(startIndex));
    return arr.toArray(new String[arr.size()]);
}
2 of 3
4

The first thought that came to my mind has been why creating always a new StringBuilder after the delimiter is found. So I changed this and called the setLength() with zero as parameter like

public static String[] split(String strToSplit, char delimiter) {
    ArrayList<String> arr = new ArrayList<String>();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < strToSplit.length(); i++) {
        char at = strToSplit.charAt(i);
        if (at == delimiter) {
            arr.add(sb.toString());
            sb.setLength(0);
        } else {
            sb.append(at);
        }
    }
    arr.add(sb.toString());
    return arr.toArray(new String[0]);
}

The next I thought, why use a StringBuilder and the CharAt(), if a indexOf() could be used, so I changed it to

public static String[] split(String strToSplit, char delimiter) {
    ArrayList<String> arr = new ArrayList<String>();
    int foundPosition = 0;
    int startIndex = 0;
    while ((foundPosition = strToSplit.indexOf(delimiter, startIndex)) >= 0) {

        arr.add(strToSplit.substring(startIndex, foundPosition));
        startIndex = foundPosition + 1;

    }
    arr.add(strToSplit.substring(startIndex));
    return arr.toArray(new String[0]);
}

You need to profile it by yourself.

🌐
Sentry
sentry.io › sentry answers › java › how to split a string in java
How to split a string in Java | Sentry
May 15, 2023 - This means it is easy to do things like split on one or more : characters by using :+. public class Main { public static void main(String[] arg) { String str = "how:to::split:::a:string:in:java"; String[] arrOfStr = str.split(":+"); for (String ...
🌐
Baeldung
baeldung.com › home › java › java string › split a string every n characters in java
Split a String Every n Characters in Java | Baeldung
January 8, 2024 - Another way to split a String object at every nth character is to use the substring method.
🌐
Real's HowTo
rgagnon.com › javadetails › java-0438.html
Split a string using String.split() - Real's Java How-to
public class StringSplit { public static void main(String args[]) throws Exception{ String testString = "Real|How|To"; // bad System.out.println (java.util.Arrays.toString(testString.split("|"))); // output : [, R, e, a, l, |, H, o, w, |, T, o] // good System.out.println (java.util.Arrays.toString(testString.split("\\|"))); // output : [Real, How, To] } } The special character needs to be escaped with a "\" but since "\" is also a special character in Java, you need to escape it again with another "\" !
🌐
Apps Developer Blog
appsdeveloperblog.com › home › java › how to split a string in java: different examples
How to Split a String in Java: Different Examples
June 4, 2023 - String characters = "a.b.c"; String[] charactersArray = characters.split("(?<=\\.)"); Let’s have a look at the complete example. import java.util.regex.Pattern; public class App { public static void main(String[] args) { String characters = "a.b.c"; String[] charactersArray = characters.split("(?<=\\.)"); for (String character : charactersArray) { System.out.println(character); } } } The output is: a.
🌐
Codefinity
codefinity.com › courses › v2 › 0bfa1111-8677-478f-bcd3-315dff1d7d40 › 421ab035-77e8-4fef-abb9-488c91c2d1f9 › 433c4bac-9f33-4b48-9be0-cdc81423c941
Learn Method split() | String Advanced
The split(String delimiter) method splits a string into an array of substrings based on the specified delimiter (a character or sequence of characters). It returns an array where each element is a substring from the original string, separated ...
🌐
W3Docs
w3docs.com › java
How to Split a String in Java | Practice with examples | W3Docs
The split() method of a compiled Pattern splits the given input sequence around matches of the pattern. Parameter for this is: input (the character sequence to be split). It returns the array of strings computed by splitting the input around ...
🌐
IONOS
ionos.com › digital guide › websites › web development › string splitting in java
How to split strings in Java - IONOS
January 6, 2025 - The method split() can be used to split strings in Java. It contains a parameter for the separator and an optional parameter for the number of sub­strings. There are also some par­tic­u­lar­i­ties to note when using the method.
🌐
Javatpoint
javatpoint.com › how-to-split-a-string-in-java-with-delimiter
How to Split a String in Java with Delimiter
How to remove a particular character from a string · String charAt() String compareTo() String concat() String contains() String endsWith() String equals() equalsIgnoreCase() String format() String getBytes() String getChars() String indexOf() String intern() String isEmpty() String join() String lastIndexOf() Java String length() Method · String replace() String replaceAll() String split() String startsWith() String substring() String toCharArray() String toLowerCase() String toUpperCase() String trim() Java Regex ·
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › java-string-split-method-example
Java String split() Method with examples
Input: "Just.a.Simple.String"; Output: ["Just", "a", "Simple", "String"] ... The ?! part in this regex is negative assertion, which it works like a not operator in the context of regular expression. The ^ is to match the beginning of the string. Together it matches any character that is not ...