In many applications you get data in a text file which is either separated using a pipe (|) symbol or a tab (/t) symbol . Now, if you want to do a quick split around that separating symbol you can easily do it using split()
method in Java which is in the String class itself. In this post we'll see example Java programs to split a String.
Refer Splitting a String using split() method in Java to read in detail about split() method.
Splitting pipe delimited String Java Example
public class SplitDemo { public static void main(String[] args) { String str = "E001|Ram|IT|India|"; // splitting String[] rec = str.split("\\|"); System.out.println("" + rec[3]); } }
Output
India
Points to note
- Since pipe (|) is also used in conditions like OR (||) so that is a special symbol and needs to be escaped.
- split() method returns the array of strings computed by splitting this string around matches of the given regular expression.
Splitting tab delimited data Java Example
You can use the following Java code snippet if you are splitting tab delimited data string.
String str = "E001 Ram IT India"; // splitting String[] recArr = str.split("\t"); for(String rec : recArr){ System.out.println(" " + rec); }
Output
E001 Ram IT India
Splitting dot delimited String Java Example
You can use the following Java code snippet if you are splitting dot (.) delimited data. Note that "." has to be escaped as it is a special symbol.
String str = "E001.Ram.IT.India"; // splitting String[] recArr = str.split("\\."); for(String rec : recArr){ System.out.println(" " + rec); }
Output
E001 Ram IT India
That's all for this topic Split a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment