Apr 22, 2012

Parse Comma Delimited List

Parse Comma Delimited List



Parsing the contents of string having some delimiter is a common task to be performed in a Java application. There are multiple ways in which strings can be parsed on the basis of delimiter in Java which includes the split method of String class and the StringTokenizer class

The following Java program parses a comma separated list of strings and then splits it based on the delimiter and generates a string array. After iterating the array, the elements of the string array thus created are printed on the console.

package com.example;


/** This class is a demo for Java Tutorial on how to parse comma separated list in Java
*
* @author Extreme Java
*
*/
public class Test {


/** This method shows how to parse string in Java
* @param args
*/
public static void main(String[] args) {
String str1 = new String("ABC,DEF,GHI,JKL,MNO,PQR,STU,VWX,YZ");

String str2[] = str1.split(",");

for (int i = 0; i < str2.length; i++) { System.out.println(str2[i]); } } }


output:
ABC
DEF
GHI
JKL
MNO
PQR
STU
VWX
YZ

As shown in the output of above program, the split() method of String class returns a string array which can be iterated to get the delimited string tokens.

1 comment:

  1. ahhhh .. apache project: http://commons.apache.org/csv/

    heaps of others: http://stackoverflow.com/questions/101100/csv-api-for-java

    ReplyDelete