Splitting String in Java with Examples


If you have a String in Java, or you are reading an external CSV, txt, or any other type of file line-by-line and want to split it based on a specific character then you can make use of the build-in split(String regex) function from String class,

Example 1: Split String with CSV Line
String csvLine = "1,2,3,4,5,6";
String[] numStrArray = csvLine.split(",");

 for (String num: numStrArray) {
   System.out.println(num);
  }
Output:

1
2
3
4
5
6



Example 2: Split String with Pipe Seperated Line
String pipeSeperatedLine = "1|2|3|4|6";
String[] numStrArray =  pipeSeperatedLine.split("\|\");

 for (String num: numStrArray) {
   System.out.println(num);
  }
Output:

1
2
3
4
5
6



Example 3: Split String with Space Separated Line
Splitting String in Java
Splitting String in Java

Top Hashtags:

Advertisements

Advertisements




Advertisements