Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Beginners Java String Split Example

 
 

Share on Google+Share on Google+

Java String Split Example

Advertisement
In this section, you will learn how to split string into different parts using spit() function.

Java String Split Example

In this section, you will learn how to split string into different parts using spit() function.

CODE

In the given below example, the first string splits where the compiler finds the delimiter '-' and second string splits where it finds the delimiter '.' . The third string splits where it finds the '.' delimiter but it will split it into only 3 parts in spite of 4 parts because we define it in the function split() that split the string into 3 parts. The string will split from the first three delimiter.

public class SplitString {

public static void main(String args[]) {
//Defining string and array 
String sample = "Sucess-need-continous-effort";
String subStr[];
System.out.println("EXAMLES OF SPLITTING STRING");
System.out.println("");

//Defining delimiter '-' and splitting string at '-'
System.out.println("Splitting string at '-'");
String delimiter = "-";
subStr = sample.split(delimiter);
for (int i = 0; i < subStr.length; i++)
System.out.println(subStr[i]);
System.out.println("");

//Defining delimiter '.' and splitting string at '.'
System.out.println("Splitting string at '.'");
sample = "Sucess.need.continous.effort";
delimiter = "\\.";
subStr = sample.split(delimiter);
for (int i = 0; i < subStr.length; i++)
System.out.println(subStr[i]);
System.out.println("");

//Defining delimiter '.' and splitting string at '.'
System.out.println("Splitting string at '.' in three part only, regardless of delimiter");
subStr = sample.split(delimiter, 3);
for (int i = 0; i < subStr.length; i++)
System.out.println(subStr[i]);
System.out.println("");

}
}

OUTPUT

EXAMLES OF SPLITTING STRING

Splitting string at '-'
Sucess
need
continous
effort

Splitting string at '.'
Sucess
need
continous
effort

Splitting string at '.' in three part only, regardless of delimiter
Sucess
need
continous.effort

Download Source Code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 7, 2012

Related Tutorials

Discuss: Java String Split Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
Isaiah
June 15, 2013
TyNsLAOrqScXQ

I can hardly read that... but it seems like the user is stppiring out all white space (except for tabs) and some tags and then joining it back into one giant string with no line breaks... looks like a big bowl of 'wrong' to me
DMCA.com