In many applications you get data in a text file which is either separated using a pipe (|) symbol or a tab symbol (/t). Now, if you want to do a quick split around that separating symbol you can easily do it using split() method which is in the String class itself.
- Refer Splitting a String using split() method in Java to read in detail about split() method.
In this post we’ll see how to split a String using split() method -
Splitting pipe delimited data - Example code
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 – Example code
You can use the following code snippet if you are splitting tab delimited data.
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 data – Example code
You can use the following 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 Splitting a String - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like -