December 2, 2022

How to Split a String in Java

This post shows how you can split a String in Java using split() method. String you need to split may be delimited using pipe, tab or spaces so let’s see how to use split() method to split such delimited data strings in Java. Note that if you are using any special symbol with in the regular expression then you do need to escape it using escape character (\).

Splitting String delimited using pipe(|) symbol - Java code

public class SplitString {
  public static void main(String[] args) {
    String str = "A001|BOA|Ronda|5000";
    String[] data = str.split("\\|");
    System.out.println("Name- " + data[2]);
  }
}
Output
Name- Ronda

Splitting data in Java delimited using tab (\t)

public class SplitString {
  public static void main(String[] args) {
    String str = "A001	BOA	Ronda	5000";
    String[] data = str.split("\t");
    System.out.println("Amount- " + data[3]);
  }
}
Output
Amount- 5000

Splitting data delimited using spaces- Java code

public class SplitString {
  public static void main(String[] args) {
    String str = "A001  BOA Ronda 5000";
    // Matches any number of spaces
    String[] data = str.split("\\s+");
    System.out.println("Amount- " + data[3]);
  }
}
Output
Amount- 5000

Splitting data delimited using single space

public class SplitString {
  public static void main(String[] args) {
    String str = "A001 BOA Ronda 5000";
    // Matches any number of spaces
    String[] data = str.split("\\s");
    System.out.println("Name- " + data[2]);
  }
}
Output
Name- Ronda

That's all for the topic How to Split a String in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment