Java String split() example

In this guide, you will learn about the String split() method in Java programming and how to use it with an example.

1. String split() Method Overview

Definition:

The split() method of Java's String class breaks the given string around matches of the given regular expression and returns an array of strings.

Syntax:

1. str.split(String regex)
2. str.split(String regex, int limit)

Parameters:

- regex: the delimiting regular expression.

- limit: the result threshold which dictates the maximum number of strings in the array.

Key Points:

-  The split() method splits this string against a given regular expression and returns a char array.

- If limit is specified and is positive, the pattern will be applied at most limit - 1 times, and the resulting array's length will not be greater than limit.

- A limit of zero or negative will cause the pattern to be applied as many times as possible, resulting in an array of length equal to or greater than limit.

2. String split() Method Example

public class SplitExample {
    public static void main(String[] args) {
        String sample = "Java,Python,C++,Ruby";

        // Splitting by comma
        String[] languages1 = sample.split(",");
        System.out.println("Splitting by comma:");
        for (String lang : languages1) {
            System.out.println(lang);
        }

        // Splitting by comma with a limit
        String[] languages2 = sample.split(",", 3);
        System.out.println("\nSplitting by comma with a limit of 3:");
        for (String lang : languages2) {
            System.out.println(lang);
        }

        // Splitting with a non-existent delimiter
        String[] languages3 = sample.split("-");
        System.out.println("\nSplitting with a non-existent delimiter:");
        for (String lang : languages3) {
            System.out.println(lang);
        }
    }
}

Output:

Splitting by comma:
Java
Python
C++
Ruby

Splitting by comma with a limit of 3:
Java
Python
C++,Ruby

Splitting with a non-existent delimiter:
Java,Python,C++,Ruby

Explanation:

In the example:

1. We begin by splitting the string using the comma as a delimiter. The split() method divides the string into an array of substrings at each comma.

2. Next, we split the string using the comma as a delimiter but with a limit of 3. This means the pattern is applied only twice, and the resulting array will contain at most 3 strings. The remaining portion after the second comma is taken as one string.

3. Lastly, we try to split the string with a non-existent delimiter ('-'). Since the delimiter isn't present in the string, the entire string is returned as a single array element.

Related Java String Class method examples

Comments