String Split

String Split is nothing but splitting string with another string. This can easily be done with Java using the String class' split(String split_string) method. This method helps to split a string with a given String and then returns the words in the form of a String array.


class StringSplit
{
public static void main(String args[])
{
// Create a string
String s1="Gowtham Gutha";

// Print s1
System.out.println(s1);

// Split it with a space
String[] a1=s1.split(" ");

// Say split char
System.out.println("Splitting character is \" \"");

// Print it
for(int i=0;i<a1.length;i++)
{
System.out.println("a1: "+a1[i]);
}


// Create a string
String s2="Gowtham;Gutha";

// Print s2
System.out.println(s2);

// Split it with ;
String[] a2=s2.split(";");

// Say split char
System.out.println("Splitting character is \";\"");

// Print it
for(int i=0;i<a2.length;i++)
{
System.out.println("a2: "+a2[i]);
}

// Splitting with strings
String st1="Gowtham Gutha";

// Two chars can also be..
String[] at1=st1.split("th");

// Say split string
System.out.println("Splitting character is \"th\"");

for(int i=0;i<at1.length;i++)
{
System.out.println("at1: "+at1[i]);
}
}
}


s1.split(" "): This method splits the string s1 into words separated by a space. Here as the string is Gowtham Gutha, only here two words are separated by a space, so Gowtham, Gutha are returned i.e. Gowtham settles in a1[0] and Gutha settles in a1[1]

s2.split(";"): This method splits the string s2 into words separated by a semicolon. It returns the words that are separated. Here as the string is Gowtham;Gutha, only here two words are separated by a semicolon, so Gowtham, Gutha are returned i.e. Gowtham settles in a2[0] and Gutha settles in a2[1].

st1.split("th"): The same thing as in the above. But here we did it with 2 characters if you can observe. In the string st1 you can calculate the no.of th, it is found to 2, so Gow, am Gu, a, are the strings that are separated by th so they will be returned and will be stored in the array at1 in order.

---------------------------------------
Output
---------------------------------------


Gowtham Gutha
Splitting character is " "
a1: Gowtham
a1: Gutha
Gowtham;Gutha
Splitting character is ";"
a2: Gowtham
a2: Gutha
Splitting character is "th"
at1: Gow
at1: am Gu
at1: a


Posted by at on

Tags: String Handling,