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(,).
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.
When you run above progrm, you will get following output:
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
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]); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
-------------------- Splitting by comma -------------------- India Delhi 200400 -------------------- Splitting by Dot -------------------- India Delhi 200400 |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.