In this tutorial, we will see how to split string in java.

How to Split String in Java:

The Java String provides a split() method to split the string into different parts by using delimiter or regular expression.

1. Java Split String using delimiter:

public class String_Split {

    public static void main(String[] args) {
        String str = "abc-pqr-xyz";
        String[] arr = str.split("-");
        for (String string : arr) {
            System.out.println(string);
        }
    }
}

On the above example, We split the abc-pqr-xyz string by using “-“ delimiter.
Output:

abc
pqr
xyz

2. How to Split String with a limit:

The limit parameter controls the number of times the delimiter is applied. If the limit is greater than zero, then the delimiter will be used at most n-1 times.

public class String_Split {

    public static void main(String[] args) {
        String str = "abc-pqr-xyz";
        String[] arr = str.split("-", 2);
        for (String string : arr) {
            System.out.println(string);
        }
    }
}

Output:

abc
pqr-xyz

3. How to Split String with Period or (.) :

Split with a period (.) operator is something different; we need to escape (\\) the dot if we want to split on a literal dot (.).

public class String_Split {

    public static void main(String[] args) {
        String str = "mail.google.com";
        String[] arr = str.split("\.");
        for (String string : arr) {
            System.out.println(string);
        }
    }
}

Output:

mail
google
com

4. How to Split String with multiple delimiters:

We can split a string with various delimiters by using pipe (|)/OR operator.

public class String_Split {

    public static void main(String[] args) {
        String str = "mail.google.com-onlinetutorialspoint.com&String_split";
        String[] arr = str.split("\.|-|&|_");
        for (String string : arr) {
            System.out.println(string);
        }
    }
}

On the above example, we split the String with multiple delimiters like (.,-,&,_)
Output:

mail
google
com
onlinetutorialspoint
com
String
split

Happy Learning 🙂