Monday, March 14, 2022

Split a String Java Program

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

  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 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

  1. Check if Given String or Number is a Palindrome Java Program
  2. Convert String to double in Java
  3. Add Double Quotes to a String Java Program
  4. Matrix Multiplication Java Program
  5. Zipping Files And Folders in Java

You may also like-

  1. Java Program to Display Prime Numbers
  2. Factorial Program in Java
  3. Quick Sort Program in Java
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. Java Stream API Tutorial
  6. Spring MessageSource Internationalization (i18n) Support
  7. Ternary Operator in Java With Examples
  8. Is String Thread Safe in Java

No comments:

Post a Comment