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

Java String split() Method with examples

Last Updated: December 1, 2024 by Chaitanya Singh | Filed Under: java

Java String split method is used for splitting a String into substrings based on the given delimiter or regular expression.

For example:

Input String: chaitanya@singh

Regular Expression: @ 

Output Substrings: {"chaitanya", "singh"}

Java String Split Method

Java Split Method Examples


We have two variants of split() method in String class.

1. String[] split(String regex): It returns an array of strings after splitting an input String based on the delimiting regular expression.

2. String[] split(String regex, int limit): This method is used when you want to limit the number of substrings. The only difference between this variant and above variant is that it limits the number of strings returned after split up. For example: split("anydelimiter", 3) would return the array of only 3 strings even if there can be more than three substrings.

What if limit is entered as a negative number?
If the limit is negative then the returned string array would contain all the substrings including the trailing empty strings, however if the limit is zero then the returned string array would contains all the substrings excluding the trailing empty Strings.

It throws PatternSyntaxException if the syntax of specified regular expression is not valid.

String split() method Example

If the limit is not defined:

public class JavaExample{
  public static void main(String args[]){
    // Input String
    String str = new String("17/09/2022");

    System.out.println("Substrings of given string:");
    /* Here we are using first variation of string split() method
     * which splits the string into substring based on the regular
     * expression, there is no limit on the substrings
     */
    String strArr[]= str.split("/");
    for (String temp: strArr){
      System.out.println(temp);
    }
  }
}

Output:

Java String split method

If positive limit is specified in the split() method: Here the limit is specified as 2 so the split method returns only two substrings.

public class JavaExample{
  public static void main(String args[]){
    // Input String
    String str = new String("17/09/2022");

    System.out.println("Two Substrings of given string:");

    //limit is set as 2 so it would return only two substrings
    String strArr[]= str.split("/", 2);
    for (String temp: strArr){
      System.out.println(temp);
    }
  }
}

Output:

String split strings with a limit

If limit is specified as a negative number: As you can see that when the limit is negative, it included the trailing empty strings in the output. See the output screenshot below.

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

    System.out.println("Substrings when limit is negative:");

    //negative limit
    String strArr[]= str.split("/", -1);
    int i=1;
    for (String temp: strArr){
      System.out.print(i+". ");
      System.out.println(temp);
      i++;
    }
  }
}

Output:

String split when limit is set to negative


Limit is set to zero: This will exclude the trailing empty strings.

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

    System.out.println("Substrings when limit is Zero:");

    //Zero limit
    String strArr[]= str.split("/", 0);
    int i=1;
    for (String temp: strArr){
      System.out.print(i+". ");
      System.out.println(temp);
      i++;
    }
  }
}

Output:

output

Difference between zero and negative limit in split() method:

  • If the limit in split() is set to zero, it outputs all the substrings but exclude trailing empty strings if present.
  • If the limit in split() is set to a negative number, it outputs all the substrings including the trailing empty strings if present.

Java String split() method with multiple delimiters

Let’s see how we can pass multiple delimiters while using split() method. In this example we are splitting input string based on multiple special characters.

public class JavaExample{
  public static void main(String args[]){
    String s = " ,ab;gh,bc;pq#kk$bb";
    String[] str = s.split("[,;#$]");

    //Total how many substrings? The array length
    System.out.println("Number of substrings: "+str.length);

    for (int i=0; i < str.length; i++) {
      System.out.println("Str["+i+"]:"+str[i]);
    }
  }
}

Output:

Number of substrings: 7
Str[0]: 
Str[1]:ab
Str[2]:gh
Str[3]:bc
Str[4]:pq
Str[5]:kk
Str[6]:bb

Lets practice few more examples:

Java Split String Examples

Example 1: Split string using word as delimiter

Here, a string (a word) is used as a delimiter in split() method.

public class JavaExample {
  public static void main(String args[])
  {
    String str = "helloxyzhixyzbye";
    String[] arr = str.split("xyz");

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

Output:

hello
hi
bye

Example 2: Split string by space

String[] strArray = str.split("\s+");

You can Split string by space using \s+ regex.

Input: "Text with spaces";
Output: ["Text", "with", "spaces"]

Example 3: Split string by pipe

String[] strArray = str.split("\|");

Split string by pipe ( | ) character using \| regex.

Input: "Text1|Text2|Text3";
Output: ["Text1", "Text2", "Text3"]

Example 4: Split string by dot ( . )

String[] strArray = str.split("\.");

You can split string by dot ( . ) using \. regex in split method.

Input: "Just.a.Simple.String";
Output: ["Just", "a", "Simple", "String"]

Example 5: Split string into array of characters

String[] strArray = str.split("(?!^)");

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 the beginning of the string, which means it splits the string on every character.

Input: "String";
Output: ["S", "t", "r", "i", "n", "g"]

Example 6: Split string by capital letters

String[] strArray = str.split("(?=\p{Lu})");

p{Lu} is a shorthand for p{Uppercase Letter}. This regex matches uppercase letter. The extra backslash is to escape the sequence. This regex split string by capital letters.

Input: "BeginnersBook.com";
Output: ["Beginners", "Book.com"]

Example 7: Split string by newline

String[] str = str.split(System.lineSeparator());

This is one of the best way to split string by newline as this is a system independent approach. The lineSeparator() method returns the character sequence for the underlying system.

Example 8: Split string by comma

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

To split the string by comma, you can pass , special character in the split() method as shown above.

❮ PreviousNext ❯

Top Related Articles:

  1. Convert Comma Separated String to HashSet in Java
  2. Split String by Newline in Java
  3. Java Code to Split String by Comma
  4. StringTokenizer in Java with Examples
  5. Split String by Pipe Character ( | ) in Java

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

Comments

  1. Khushboo bansal says

    March 18, 2018 at 2:29 PM

    Is it right to say that 28 is present at array1[0], 12 at array1[1] and 2013 at array1[2]?
    I am really confused right now.Please help.

    Reply
    • Chaitanya Singh says

      December 19, 2018 at 10:19 AM

      Thats correct.

      Reply
  2. Susan says

    November 27, 2018 at 11:13 PM

    It would be helpful to include some examples that require use of the escape characters and which characters need them. It is one thing I was looking for. Once I realized that “|” needed “\\|”, my split worked like a champ.

    Thanks for showing these using small code bits. It really does make a difference.

    Reply
    • Chaitanya Singh says

      December 19, 2018 at 10:19 AM

      I have added more examples.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

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