Split() String Method in Java: How to Split String with Example

What is split() string in Java?

StrSplit() method allows you to break a string based on specific Java string delimiter. Mostly the Java string split attribute will be a space or a comma(,) with which you want to break or split the string

Syntax

public String split(String regex)
public String split(String regex, int limit)  
Parameter

Split String Example

Below example shows how to split a string in Java with delimiter:

Suppose we have a string variable named strMain formed of a few words like Alpha, Beta, Gamma, Delta, Sigma – all separated by the comma (,).

Consider the following code of split method in Java –

class StrSplit2{
  public static void main(String []args){
   String strMain = "Alpha, Beta, Delta, Gamma, Sigma";
    String[] arrSplit_2 = strMain.split(", ", 3);
    for (int i=0; i < arrSplit_2.length; i++){
      System.out.println(arrSplit_2[i]);
    }
  }
}
Output:
Alpha
Beta
Delta, Gamma, Sigma

How to Split a string in Java by Space

Consider a situation, wherein you want to split a string by space. Let’s consider an example here; we have a split string Java variable named strMain formed of a few words Welcome to gtupapers.

public class StrSplit3{  
public static void main(String args[]){  
String strMain ="Welcome to gtupapers"; 
String[] arrSplit_3 = strMain.split("\\s");
    for (int i=0; i < arrSplit_3.length; i++){
      System.out.println(arrSplit_3[i]);
    }
  }
}

Output:

Welcome
to 
gtupapers

 

YOU MIGHT LIKE: