Question

How to Split a String in Java Using a Delimiter

javastringsplit

Question

I want to split a string in Java using a delimiter. For example, I want to split the string "004-034556" into two separate strings using "-" as the delimiter:

String part1 = "004";
String part2 = "034556";

In other words, the first result should contain the characters before '-', and the second result should contain the characters after '-'.

I also want to check whether the string contains the delimiter '-' before splitting.

Short Answer

By the end of this page, you will understand how to split a string in Java using a delimiter, how String.split() works, how to check whether a delimiter exists with contains() or indexOf(), and how to safely handle cases where the delimiter is missing or appears multiple times.

Concept

In Java, strings are instances of the String class, which provides built-in methods for searching and dividing text.

The main method used to split text is:

split()

It breaks a string into smaller pieces based on a separator, also called a delimiter.

For example:

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

This produces an array containing:

  • parts[0] → "004"
  • parts[1] → "034556"

This matters because splitting strings is very common in real programs. Developers use it when working with:

  • CSV data
  • IDs like user-123
  • file paths
  • API responses
  • configuration values
  • logs and structured text

A related concept is checking whether the delimiter exists before splitting. In Java, you can do that with:

value.contains("-")

or:

value.indexOf('-') != -1

This helps prevent errors such as trying to read a second part when the string does not actually contain the delimiter.

One important detail: split() uses a regular expression pattern, not just plain text. For "-", that is simple and safe, but some delimiters like ".", "|", or "*" need escaping.

Mental Model

Think of a string like a sentence written on a strip of paper, and the delimiter is a cut mark.

If the paper looks like this:

004-034556

then - is the place where you cut it into pieces:

  • left side: 004
  • right side: 034556

Before cutting, you may want to check whether the cut mark exists at all. If there is no -, there is nothing to split.

So the process is:

  1. Look for the cut mark.
  2. If it exists, split the text.
  3. Read the pieces from the result array.
Take Quiz

Syntax and Examples

Basic syntax

String[] parts = text.split("-");
  • text is the original string
  • "-" is the delimiter
  • the result is a String[] array

Example: split into two parts

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

String part1 = parts[0];
String part2 = parts[1];

System.out.println(part1); // 004
System.out.println(part2); // 034556

This works because the string contains one -, so the split produces exactly two parts.

Example: check before splitting

String value = "004-034556";

if (value.contains("-")) {
    String[] parts = value.split("-");
    System.out.println("Before dash: " + parts[0]);
    System.out.println("After dash: " + parts[1]);
} else {
    System.out.println("Delimiter not found");
}

This is safer because it avoids assuming the delimiter is always present.

Example: using indexOf()

String value = "004-034556";

if (value.indexOf('-') != -1) {
    String[] parts = value.split("-");
    System.out.println(parts[0]);
    System.out.println(parts[1]);
}

indexOf('-') returns the position of -, or -1 if it does not exist.

Example: split only once

If a string might contain more than one delimiter, but you only want two parts, use a limit:

String value = "004-034-556";
String[] parts = value.split("-", 2);

System.out.println(parts[0]); // 004
System.out.println(parts[1]); // 034-556

This is useful when only the first delimiter should divide the string.

Step by Step Execution

Consider this code:

String value = "004-034556";

if (value.contains("-")) {
    String[] parts = value.split("-");
    String part1 = parts[0];
    String part2 = parts[1];

    System.out.println(part1);
    System.out.println(part2);
}

Step-by-step

  1. value is assigned the text "004-034556".
  2. value.contains("-") checks whether - exists in the string.
  3. Since - is present, the if block runs.
  4. value.split("-") cuts the string at the dash.
  5. Java creates a String[] array with two values:
    • index 0 = "004"
    • index 1 = "034556"
  6. part1 gets parts[0], which is "004".
  7. part2 gets parts[1], which is "034556".
  8. The program prints both values.

Result

004
034556

What if there is no delimiter?

String value = "004034556";

Then:

  • value.contains("-") is false
  • the if block does not run
  • no split happens
  • you avoid accessing parts[1] when it does not exist

Real World Use Cases

Splitting strings by delimiters appears everywhere in Java programs.

Common examples

  • User input parsing

    • Input like name:John can be split into key and value.
  • Product or account codes

    • 004-034556 can be split into a category code and item number.
  • CSV and text file processing

    • A line like Alice,24,London can be split by ,.
  • Log processing

    • A log entry like ERROR|Database unavailable can be split into level and message.
  • Configuration strings

    • A value like host=localhost can be split into setting name and setting value.
  • URL or route parsing

    • Paths or slugs often need to be divided into segments.

In all of these cases, checking whether the delimiter exists first helps make the code more reliable.

Take Quiz

Real Codebase Usage

In real projects, developers usually do more than just call split().

Common patterns

Guard clause before splitting

if (!value.contains("-")) {
    return;
}

This exits early if the input is not in the expected format.

Validation before using array indexes

String[] parts = value.split("-");
if (parts.length == 2) {
    String left = parts[0];
    String right = parts[1];
}

This prevents ArrayIndexOutOfBoundsException.

Split only once for structured values

String[] parts = value.split("-", 2);

This is common when the second part may contain the delimiter again.

Trimming spaces after splitting

String value = "004 - 034556";
String[] parts = value.split("-");
String left = parts[0].trim();
String right = parts[1].trim();

Useful when data comes from users or files.

Manual splitting with indexOf() and substring()

In some codebases, developers prefer explicit control:

int dashIndex = value.indexOf('-');
if (dashIndex != -1) {
    String left = value.substring(0, dashIndex);
    String right = value.substring(dashIndex + 1);
}

This is especially readable when you only need the text before and after the first delimiter.

Common Mistakes

1. Assuming the delimiter always exists

Broken code:

String value = "004034556";
String[] parts = value.split("-");
String part2 = parts[1];

Problem:

  • If there is no -, parts will only have one element.
  • Accessing parts[1] throws ArrayIndexOutOfBoundsException.

Fix:

if (value.contains("-")) {
    String[] parts = value.split("-");
    if (parts.length >= 2) {
        String part2 = parts[1];
    }
}

2. Forgetting that split() returns an array

Broken code:

String part = value.split("-");

Problem:

  • split() returns String[], not a single String.

Fix:

String[] parts = value.split("-");

3. Ignoring regular expression rules

Broken code:

String value = "a.b";
String[] parts = value.split(".");

Problem:

  • . in regex means “any character”, not a literal dot.

Fix:

String[] parts = value.split("\\.");

4. Not handling multiple delimiters correctly

String value = "a-b-c";
String[] parts = value.split("-");

This creates three parts, not two.

If you only want two pieces, use:

String[] parts = value.split("-", 2);

5. Forgetting to trim whitespace

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

Result:

  • parts[0] is "004 "
  • parts[1] is " 034556"

Fix:

String left = parts[0].trim();
String right = parts[1].trim();

Comparisons

split() vs indexOf() + substring()

ApproachBest forProsCons
split("-")General splitting into multiple partsShort and easy to readUses regex, returns an array
indexOf('-') + substring()Splitting around one known delimiterExplicit control, good for two partsMore manual code

contains() vs indexOf()

MethodReturnsGood whenExample
contains("-")true or falseYou only need to know if it existsvalue.contains("-")
indexOf('-')position or -1You need the location toovalue.indexOf('-')

split("-") vs split("-", 2)

CodeResult for "a-b-c"Use when
split("-")`[
"a", "b", "c"]`You want all pieces
split("-", 2)`[
"a", "b-c"]`You only want two pieces

Which should you choose?

  • Use contains() when you only want to check if a delimiter exists.
  • Use split() when you want the pieces as an array.
  • Use split(..., 2) when only the first delimiter should split the string.
  • Use indexOf() with substring() when you want very explicit control over two parts.
Take Quiz

Cheat Sheet

Quick reference

Check if delimiter exists

value.contains("-")

or

value.indexOf('-') != -1

Split by delimiter

String[] parts = value.split("-");

Access parts

String part1 = parts[0];
String part2 = parts[1];

Safer version

if (value.contains("-")) {
    String[] parts = value.split("-");
    if (parts.length >= 2) {
        String part1 = parts[0];
        String part2 = parts[1];
    }
}

Split only once

String[] parts = value.split("-", 2);

Manual alternative

int index = value.indexOf('-');
if (index != -1) {
    String left = value.substring(0, index);
    String right = value.substring(index + 1);
}

Important rule

split() uses regular expressions.

Characters like these may need escaping:

  • .
  • |
  • *
  • +
  • ?
  • ( )
  • [ ]
  • { }

Common edge cases

  • No delimiter present
  • Multiple delimiters present
  • Spaces around the delimiter
  • Empty text before or after the delimiter

FAQ

How do I split a string by - in Java?

Use split("-"):

String[] parts = value.split("-");

How can I check if a string contains a dash in Java?

Use either:

value.contains("-")

or:

value.indexOf('-') != -1

What happens if split() does not find the delimiter?

It returns an array with one element: the original string.

Why does split() return an array?

Because a string may be split into many parts, not just two.

Should I use split() or substring() in Java?

Use split() for simple delimiter-based splitting. Use indexOf() and substring() when you want precise control over one split point.

Can I split a string into only two parts?

Yes:

String[] parts = value.split("-", 2);

Does split() work with all delimiters?

Yes, but remember that split() uses regex. Some delimiters must be escaped, such as . and |.

Take Quiz

Mini Project

Description

Build a small Java program that reads a code like 004-034556, checks whether it contains a dash, and then prints the left and right parts separately. This demonstrates safe string parsing, validation, and basic array handling.

Goal

Create a Java program that safely splits a string by - and handles invalid input gracefully.

Requirements

[ "Create a string variable containing a code such as 004-034556.", "Check whether the string contains the - delimiter before splitting.", "If the delimiter exists, print the part before and after the dash.", "If the delimiter does not exist, print a helpful error message.", "Use Java string methods only." ]

Take Quiz

Keep learning

Related questions

View more