Wednesday , January 17 2018
Home / java / Java String split example

Java String split example

In this tutorial, I am going to show you how to use split Java string.

Java String split :

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

Java String Split 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.

abc
pqr
xyz

Java String Split limit:

The limit parameter controls the number of times the delimiter is applied. If the limit is greater than zero n then the delimiter will be applied 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);
        }
    }
}

abc
pqr-xyz

String split with Period or (.) :

Split with 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);
        }
    }
}

mail
google
com

String split with multiple delimiters :

We can split a string with multiple 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 (.,-,&,_)

mail
google
com
onlinetutorialspoint
com
String
split

Happy Learning 🙂

About chandrashekhar

Hi
Folks,
you have reach this so far, that shows you like what you are learning. Then why don’t you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Recommended

Java MD5 Encryption Example

In this tutorial, I am going to show you how to use Java MD5 Encryption. …

Leave a Reply

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