How to split a string in Java

riyana Source

I have a string, "004-034556", that I want to split into two strings:


That means the first string will contain the characters before '-', and the second string will contain the characters after '-'. I also want to check if the string has '-' in it. If not, I will throw an exception. How can I do this?



answered 8 years ago BalusC #1

Just use the appropriate method: String#split().

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

Note that this takes 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".

So, if you want to split on e.g. 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 period.

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

answered 8 years ago jjnguy #2

String[] result = yourString.split("-");
if (result.length != 2) 
     throw new IllegalArgumentException("String not in correct format");

This will split your string into 2 parts. The first element in the array will be the part containing the stuff before the -, and the 2nd element in the array will contain the part of your string after the -.

If the array length is not 2, then the string was not in the format: string-string.

Check out the split() method in the String class.

answered 8 years ago secmask #3

String[] out = string.split("-");

should do thing you want. String class has many method to operate with string.

answered 8 years ago Michael Konietzka #4

The requirements left room for interpretation. I recommend writing a method,

public final static String[] mySplit(final String s)

which encapsulate this function. Of course you can use String.split(..) as mentioned in the other answers for the implementation.

You should write some unit-tests for input strings and the desired results and behaviour.

Good test candidates should include:

 - "0022-3333"
 - "-"
 - "5555-"
 - "-333"
 - "3344-"
 - "--"
 - ""
 - "553535"
 - "333-333-33"
 - "222--222"
 - "222--"
 - "--4555"

With defining the according test results, you can specify the behaviour.

For example, if "-333" should return in [,333] or if it is an error. Can "333-333-33" be separated in [333,333-33] or [333-333,33] or is it an error? And so on.

answered 8 years ago Rob Hague #5

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 " + +
                               ", second part is " + + ".");
        } else {
            System.out.println(s + " does not match.");

    public static void main(String[] args) {

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:


The parentheses denote the capturing groups; the string that matched that part of the regexp can be accessed by the 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

answered 6 years ago Mnyikka #6

// This leaves the regexes issue out of question
// But we must remember that each character in the Delimiter String is treated
// like a single delimiter        

public static String[] SplitUsingTokenizer(String subject, String delimiters) {
   StringTokenizer strTkn = new StringTokenizer(subject, delimiters);
   ArrayList<String> arrLis = new ArrayList<String>(subject.length());


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

answered 6 years ago SHUNMUGA RAJ PRABAKARAN #7

You can try like this also

 String concatenated_String="hi^Hello";

 String split_string_array[]=concatenated_String.split("\\^");

answered 6 years ago user2045376 #8

Sometimes if you want to split string containing + then it won't split; instead you will get a runtime error. In that case, first replace + to _ and then split:

 this.text=text.replace("/", "_");
            String temp[]=text.split("_");

answered 5 years ago Akhilesh Dhar Dubey #9

public class SplitTest {

    public static String[] split(String text, String delimiter) {
        java.util.List<String> parts = new java.util.ArrayList<String>();

        text += delimiter;

        for (int i = text.indexOf(delimiter), j=0; i != -1;) {
            String temp = text.substring(j,i);
            if(temp.trim().length() != 0) {
            j = i + delimiter.length();
            i = text.indexOf(delimiter,j);

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

    public static void main(String[] args) {
        String str = "004-034556";
        String delimiter = "-";
        String result[] = split(str, delimiter);
        for(String s:result)

answered 5 years ago David #10

The fastest way, which also consumes the least resource could be:

String s = "abc-def";
int p = s.indexOf('-');
if (p >= 0) {
    String left = s.substring(0, p);
    String right = s.substring(p + 1);
} else {
  // s does not contain '-'

answered 5 years ago eis #11

Assuming, that

  • you don't really need regular expressions for your split
  • you happen to already use apache commons lang in your app

The easiest way is to use StringUtils#split(java.lang.String, char). That's more convenient than the one provided by Java out of the box if you don't need regular expressions. Like its manual says, it works like this:

A null input String returns null.

 StringUtils.split(null, *)         = null
 StringUtils.split("", *)           = []
 StringUtils.split("a.b.c", '.')    = ["a", "b", "c"]
 StringUtils.split("a..b.c", '.')   = ["a", "b", "c"]
 StringUtils.split("a:b:c", '.')    = ["a:b:c"]
 StringUtils.split("a b c", ' ')    = ["a", "b", "c"]

I would recommend using commong-lang, since usually it contains a lot of stuff that's usable. However, if you don't need it for anything else than doing a split, then implementing yourself or escaping the regex is a better option.

answered 4 years ago sandeep vanama #12

Use org.apache.commons.lang.StringUtils' split method which can split strings based on the character or string you want to split.

Method signature:

public static String[] split(String str, char separatorChar);

In your case, you want to split a string when there is a "-".

You can simply do as follows:

String str = "004-034556";

String split[] = StringUtils.split(str,"-");



Assume that if - does not exists in your string, it returns the given string, and you will not get any exception.

answered 4 years ago RajeshVijayakumar #13

You can split a string by a line break by using the following statement:

String textStr[] = yourString.split("\\r?\\n");

You can split a string by a hyphen/character by using the following statement:

String textStr[] = yourString.split("-");

answered 3 years ago Vitalii Fedorenko #14

For simple use cases String.split() should do the job. If you use guava, there is also a Splitter class which allows chaining of different string operations and supports CharMatcher:


answered 3 years ago Keshav Pradeep Ramanath #15

One way to do this is to run through the String in a for-each loop and use the required split character.

public class StringSplitTest {

    public static void main(String[] arg){
        String str = "004-034556";
        String split[] = str.split("-");
        System.out.println("The split parts of the String are");
        for(String s:split)


The split parts of the String are:

answered 3 years ago Ravindra babu #16

String Split with multiple characters using Regex

public class StringSplitTest {
     public static void main(String args[]) {
        String s = " ;String; String; String; String, String; String;;String;String; String; String; ;String;String;String;String";
        //String[] strs = s.split("[,\\s\\;]");
        String[] strs = s.split("[,\\;]");
        System.out.println("Substrings length:"+strs.length);
        for (int i=0; i < strs.length; i++) {


Substrings length:17
Str[2]: String
Str[3]: String
Str[4]: String
Str[5]: String
Str[6]: String
Str[10]: String
Str[11]: String

But do not expect the same output across all JDK versions. I have seen one bug which exists in some JDK versions where the first null string has been ignored. This bug is not present in the latest JDK version, but it exists in some versions between JDK 1.7 late versions and 1.8 early versions.

answered 2 years ago Divyesh Kanzariya #17

Check out the split() method in the String class on javadoc.

String data = "004-034556-1212-232-232";
int cnt = 1;
for (String item : data.split("-")) {
        System.out.println("string "+cnt+" = "+item);

Here many examples for split string but I little code optimized.

answered 2 years ago i_am_zero #18

Please don't use StringTokenizer class as it is a legacy class that is retained for compatibility reasons, and its use is discouraged in new code. And we can make use of the split method as suggested by others as well.

String[] sampleTokens = "004-034556".split("-");

And as expected it will print:

[004, 034556]

In this answer I also want to point out one change that has taken place for split method in Java 8. The String#split() method makes use of Pattern.split, and now it will remove empty strings at the start of the result array. Notice this change in documentation for Java 8:

When there is a positive-width match at the beginning of the input sequence then an empty leading substring is included at the beginning of the resulting array. A zero-width match at the beginning however never produces such empty leading substring.

It means for the following example:

String[] sampleTokensAgain = "004".split("");

we will get three strings: [0, 0, 4] and not four as was the case in Java 7 and before. Also check this similar question.

answered 2 years ago Ravi Pandey #19


public class BreakString {

  public static void main(String args[]) {

    String string = "004-034556-1234-2341";
    String[] parts = string.split("-");

    for(int i=0;i<parts.length;i++) {

answered 2 years ago Shivanandam Sirmarigari #20

String str="004-034556"
String[] sTemp=str.split("-");// '-' is a delimiter

string1=004 // sTemp[0];

answered 2 years ago Somaiah Kumbera #21

With Java 8:

    List<String> stringList = Pattern.compile("-")

    stringList.forEach(s -> System.out.println(s));

answered 2 years ago Sarat Chandra #22

You can use Split():


public class Splitting

    public static void main(String args[])
        String Str = new String("004-034556");
        String[] SplittoArray = Str.split("-");
        String string1 = SplittoArray[0];
        String string2 = SplittoArray[1];

Else, you can use StringTokenizer:

import java.util.*;
public class Splitting
    public static void main(String[] args)
        StringTokenizer Str = new StringTokenizer("004-034556");
        String string1 = Str.nextToken("-");
        String string2 = Str.nextToken("-");

answered 2 years ago SAM Jr #23

String s="004-034556";
for(int i=0;i<s.length();i++)

As mentioned by everyone, split() is the best option which may be used in your case. An alternative method can be using substring().

answered 2 years ago Akshay Gaikwad #24

Here are two ways two achieve it.

WAY 1: As you have to split two numbers by a special character you can use regex

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

public class TrialClass
    public static void main(String[] args)
        Pattern p = Pattern.compile("[0-9]+");
        Matcher m = p.matcher("004-034556");


WAY 2: Using the string split method

public class TrialClass
    public static void main(String[] args)
        String temp = "004-034556";
        String [] arrString = temp.split("-");
        for(String splitString:arrString)

answered 2 years ago KIBOU Hassan #25

To split a string, use String.split(regex):

String phone = "004-034556";
String[] output = phone.split("-");



answered 2 years ago Rohit-Pandey #26

You can simply use StringTokenizer to split a string in two or more parts whether there are any type of delimiters:

StringTokenizer st = new StringTokenizer("004-034556", "-");

answered 1 year ago user7973776 #27

From the documentation:

public String[] split(String regex,int limit) Splits this string around matches of the given regular expression. The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

Basically you can do something like this:

String s = "123-456-789-123"; // The String to be split
String[] array = s.split("-"); // Split according to the hyphen and put them in an array
for(String subString : array){ // Cycle through the array



answered 1 year ago Aditya Singh #28

 String string = "004^034556-34";
 String[] parts = string.split(Pattern.quote("^"));

If you have a special character then you can use Patter.quote. If you simply have dash (-) then you can shorten the code:

 String string = "004-34";
 String[] parts = string.split("-");

If you try to add other special character in place of dash (^) then the error will generate ArrayIndexOutOfBoundsException. For that you have to use Pattern.quote.

answered 10 months ago Dmytro Shvechikov #29

To summarize: there are at least five ways to split a string in Java:

  1. String.split():

    String[] parts ="10,20".split(",");
  2. Pattern.compile(regexp).splitAsStream(input):

    List<String> strings = Pattern.compile("\\|")
  3. StringTokenizer (legacy class):

    StringTokenizer strings = new StringTokenizer("Welcome to EXPLAINJAVA.COM!", ".");
        String substring = strings.nextToken();
  4. Google Guava Splitter:

    Iterable<String> result = Splitter.on(",").split("1,2,3,4");
  5. Apache Commons StringUtils:

    String[] strings = StringUtils.split("1,2,3,4", ",");

So you can choose the best option for you depending on what you need, e.g. return type (array, list, or iterable).

Here is a big overview of these methods and the most common examples (how to split by dot, slash, question mark, etc.)

answered 9 months ago None #30

I just wanted to write an algorithm instead of using Java built-in functions:

public static List<String> split(String str, char c){
    List<String> list = new ArrayList<>();
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < str.length(); i++){
        if(str.charAt(i) != c){
            if(sb.length() > 0){
                sb = new StringBuilder();

    if(sb.length() >0){
    return list;

answered 8 months ago KIBOU Hassan #31

To split a string, uses String.split(regex). Review the following examples :

String data = "004-034556";
String[] output = data.split("-");



Note This split (regex) takes a regex as an argument, remember to escape the regex special characters, like period/dot.

comments powered by Disqus