Wednesday, February 6, 2019

Split a String in Java Example Programs

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 in Java which is in the String class itself. In this post we'll see example Java programs to split a String.

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 in Java Example Programs. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Check Whether Given String/Number is a Palindrome or Not
  2. Converting String to double - Java Program
  3. How to Add Double Quotes to a String - Java Program
  4. Matrix Multiplication Java Program
  5. Zipping files in Java

You may also like-

  1. Displaying prime numbers - Java program
  2. Factorial program in Java
  3. How to convert Array to ArrayList in Java
  4. fail-fast Vs fail-safe iterator in Java
  5. Stream API in Java 8
  6. What is Dependency Injection in Spring
  7. Ternary operator in Java
  8. String and thread-safety in Java