Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 938

Splitting a String - Java Program

$
0
0

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.

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

  1. Since pipe (|) is also used in conditions like OR (||) so that is a special symbol and needs to be escaped.
  2. 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

  1. Check whether a given String/Number is a palindrome or not
  2. Converting string to double - Java Program
  3. How to add double quotes to a String
  4. Matrix Multiplication Java Program
  5. Zipping files in Java

You may also like -

>>>Go to Java Programs page


Viewing all articles
Browse latest Browse all 938

Trending Articles