split string java

Java String Split

The split word indicates divide particular words into smaller words. In java, we have an inbuilt Split method of String Class. Split Method has the functionality to split the String-based of some delimiter.

The split method splits a String into an array of substrings given a specific delimiter. It returns the array of String.

Java String Split Syntax

public String[] split(String regex);
public String[] split(String regex, int limit);

In Java, String class has two types of Split function.

1 ) public String [] split(String regex): Accept only Regular Expression.
2 ) public String [] split(String regex, int limit): Accept two parameters. One Regular Expression and another one is Limit.

1 ) String regex : regex means that particular value, from which point we want to break give String.

Example: In the following String, we want to break from ” , “.

String fullStr = “JAVA,PHP,WORDPRESS,MYSQL,DATABASE”;
fullStr.split(“,”);      // It will returns the array of sub strings. 

class SplitExample{
  public static void main(String []args){
    String fullStr = "JAVA,PHP,WORDPRESS,MYSQL,DATABASE";
    String[] arrSplit = fullStr.split(",");
    for (int i=0; i < arrSplit.length; i++){
      System.out.println(arrSplit[i]);
    }
  }
}

Output: 

JAVA
PHP
WORDPRESS
MYSQL
DATABASE

2 ) int limit : limit is optional parameter of split method. It indicates the total elements of given String.

class SplitExample{
  public static void main(String []args){
    String fullStr = "JAVA,PHP,WORDPRESS,MYSQL,DATABASE";
    String[] arrSplit = fullStr.split(",",2);
    for (int i=0; i < arrSplit.length; i++){
      System.out.println(arrSplit[i]);
    }
  }
}

Output: 

JAVA
PHP,WORDPRESS,MYSQL,DATABASE

More Related Post

Thanks for the reading post. I hope you like and understand the post. If you have any doubt regarding this post please comment below.

Leave a comment

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

0 0 0
FOLLOW ON