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