BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to Split a String in Java with Delimiter

Last Updated: September 21, 2022 by Chaitanya Singh | Filed Under: java

In this guide, you will learn how to split a string in java with delimiter. There are three ways you can split a string in java, first and preferred way of splitting a string is using the split() method of string class. The second way is to use the Scanner class. Other way is using the StringTokenizer class, which is a legacy class and not recommended anymore.

Three ways to Split a String in Java with Delimiter

  1. Using split() method of String class
  2. Using Scanner class useDelimiter() method
  3. Using StringTokenizer class

1. Using split() method of String class

This method has following two variants:

  • split(String regex)
  • split(String regex, int limit)

Example of split(String regex): We can pass a regular expression (regex) as delimiter in this method. In the following example, we are passing comma ( , ) in this method to break the string using comma as delimiter. You can pass any delimiter such as dot ( . ), hyphen( – ), whitespace (” “), pipe ( | ), any character or string.

public class JavaExample
{
  public static void main(String args[])
  {
    //string that contains comma
    String str = "Steve, Ram and Paul";

    //We want to break the string using comma, so delimiter is
    //specified as comma. You can break the the string using
    //any delimiter such as dot, backslash, pipe, tab etc
    String[] strArray = str.split(",");
    for(String s: strArray){
      System.out.println(s);
    }
  }
}  

Output:

Split a String in Java using split() method

Example 2: Passing a regular expression to break the input string using multiple delimiters.

public class JavaExample
{
  public static void main(String args[])
  {
    String str = "This is a String,with.multiple|delimiters";

    //breaking the string using multiple delimiters
    //pass all the delimiters, you want to use inside
    //double quotes. Here, we passing dot, comma and pipe char
    //and a space as delimiters.
    String[] strArray = str.split("[,.| ]");

    for(String s: strArray){
      System.out.println(s);
    }
  }
}  

Output:

Example of split(String regex, int limit): This is second variant of split() method.

public class JavaExample
{
  public static void main(String args[])
  {
    String str = "hi/hello/bye///";

    //limit is positive
    String[] strArray = str.split("/", 2);

    System.out.println("Limit is Positive:");
    int i=1;
    for(String s: strArray){
      System.out.print(i+". ");
      System.out.println(s);
      i++;
    }

    //limit is negative
    String[] strArray2 = str.split("/", -5);
    System.out.println("Limit is Negative:");
    int j=1;
    for(String s2: strArray2){
      System.out.print(j+". ");
      System.out.println(s2);
      j++;
    }

    //limit is zero
    String[] strArray3 = str.split("/", 0);
    System.out.println("Limit is zero:");
    int k=1;
    for(String s3: strArray3){
      System.out.print(k+". ");
      System.out.println(s3);
      k++;
    }
  }
}  

Output:

Split String using Pipe Symbol:

public class JavaExample
{
  public static void main(String args[])
  {
    String str = "Welcome|Home";
    String[] strArray = str.split("|");
    for(String s: strArray){
      System.out.println(s);
    }
  }
}

Output: This produced the unexpected output. Instead of breaking the string using pipe symbol, it splits the string into single characters. In the next program, we will fix this.

W
e
l
c
o
m
e
|
H
o
m
e

The reason that we got the above output is because this regular expression is evaluated as a logical OR operator, instead of a pipe symbol. To fix this, you can either use escape sequence like this: str.split(“\\|”) or use the brackets like this: str.split(“[|]”). Let’s see the program with escape sequence:

public class JavaExample
{
  public static void main(String args[])
  {
    String str = "Welcome|Home";

    //Now we are using escape sequence before the pipe
    //You can also call method like this:
    //str.split("[|]")
    String[] strArray = str.split("\\|");
    for(String s: strArray){
      System.out.println(s);
    }
  }
}

Output:

Welcome
Home

2. Using Scanner class useDelimiter() method

Scanner.next() method: It splits the string using the whitespace as a default delimiter. You cannot specify a delimiter in Scanner.next() method. To specify a delimiter, you can use the useDelimiter() method of Scanner class.

import java.util.Scanner;
public class JavaExample
{
  public static void main(String[] args)
  {
    String str="Welcome to BeginnersBook.com";
    Scanner scan = new Scanner(str);
    //break the string using whitespace
    while (scan.hasNext())
    {
      System.out.println(scan.next());
    }
    scan.close();
  }
}  

Output:

Welcome
to
BeginnersBook.com

Scanner.useDelimiter() method: You can specify a delimiter and then read the substrings using Scanner.next() method. In the following example, we have provided multiple delimiters (space and dot) inside brackets.

import java.util.Scanner;
public class JavaExample
{
  public static void main(String[] args)
  {
    String str="Welcome to BeginnersBook.com";
    Scanner scan = new Scanner(str);
    //whitespace and dot delimiters are inside brackets
    scan.useDelimiter("[ .]");
    while (scan.hasNext())
    {
      System.out.println(scan.next());
    }
    scan.close();
  }
}  

Output:

3. Using StringTokenizer class

StringTokenizer is a legacy class that belongs to java.util package. We can use this class to break a string into multiple substrings, called tokens.

There are two methods that come into play while using this class:

public boolean hasMoreTokens(): This method returns a boolean value true or false. It returns true if a substring is available to be read by nextToken() method.

public String nextToken(): It returns the token and moves to the next token.

import java.util.StringTokenizer;
public class JavaExample
{
  public static void main(String[] args)
  {
    String str = "100-200-300";

    //specify the delimiter in constructor of StringTokenizer class
    StringTokenizer strTokens = new StringTokenizer(str, "-");

    //checks if the next token is present
    while (strTokens.hasMoreTokens())
    {
      //displays the token
      System.out.println(strTokens.nextToken());
    }
  }
}  

Output:

100
200
300

FAQ

What is delimiter in Java?

A delimiter is a character or a symbol that marks the beginning and end of a sub-data unit inside a main data unit. In context of strings, a delimiter marks the beginning and end of a substring.

What is the best way of splitting a string in Java?

The String.split() method is the best way of splitting a string in Java. This method is robust, easy to use and supports regular expression (regex). Using regex, we can specify multiple delimiters inside split() method.

What is return type of string split?

String.split() method returns an array of string type. The elements of string array, represents the substrings that we get after using split() method.

❮ PreviousNext ❯

Top Related Articles:

  1. Convert Comma Separated String to HashSet in Java
  2. Java String substring() Method with examples
  3. Split String by Newline in Java
  4. When to use ArrayList and LinkedList in Java
  5. StringTokenizer in Java with Examples

Tags: Java-Strings

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap