How to split a String in java

In this post, we will see how to split a String by delimiter in java. Sometimes, we need to split a String by delimiter
for example: while reading a csv file, we need to split string by comma(,).

We will use String class's split method to split a String. This split(regex)  takes a regex as a argument,  so we need to escape some regex special character for example dot(.).  Split method returns a array of String.

Example:

package org.arpit.java2blog;

public class StringSplitMain {
 public static void main(String args[])
 {
  // Splitting String separated by comma
  System.out.println("--------------------");
  System.out.println("Splitting by comma");
  System.out.println("--------------------");
  String str= "India,Delhi,200400";
  String[] strArr=str.split(",");
  for (int i = 0; i < strArr.length; i++) {
  System.out.println(strArr[i]);
 }
  
 // Splitting String by dot(.)
 // We need to put escape character in case of . as it is regex special character
  System.out.println("--------------------");
  System.out.println("Splitting by Dot");
  System.out.println("--------------------");
  String strDot= "India.Delhi.200400";
  String[] strArrDot=strDot.split("\\.");
  for (int i = 0; i < strArrDot.length; i++) {
  System.out.println(strArrDot[i]);
 } 
  
 }
}

When you run above progrm, you will get following output:
--------------------
Splitting by comma
--------------------
India
Delhi
200400
--------------------
Splitting by Dot
--------------------
India
Delhi
200400


Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012