Split() in Java

 

Split in Java

In our earlier tutorial we have seen about String Tokenizer class in Java. And we have given Split method from String class which will be an alternate since String Tokenizer is legacy class. So its recommended to use split method from String class instead of StringTokenizer. So lets see whats the use if split method and how we can use in Java by using simple example. 

Split method used to search for the match as specified in the argument and splits the string and stores into an String array. There are 2 types of split methods in String class,

String str = "Hello how are you";
String arr[] = str.split(" ");

will give output as below, since we are splitting by space " "
Hello
how
are
you



String str = "Hello how are you";
String arr[] = str.split(" ", 2);

will give output as below, here we are requesting to split the string with the array size as 2. so remaining complete string will be stored in last array as below
Hello
how are you


Lets see simple java example with their output.


public class SplitTest {
 
 public static void main(String[] args) {
  String str = "Hello how are you";
  
  String arr[] = str.split(" ");
  for (String string : arr) {
   System.out.println(string);
  }
  
  System.out.println("-------------------------------");
  
  String arr1[] = str.split(" ",3);
  for (String string : arr1) {
   System.out.println(string);
  }
 }
}


OUTPUT:


Hello
how
are
you
-------------------------------
Hello
how
are you






No comments:
Write comments