Pin It

How to parse a comma-separated String using String's split method and StringTokenizer class in Java ?.

Program to demonstrate how to parse a comma-separated String using String's split method and StringTokenizer class in Java.

package com.hubberspot.examples;

import java.util.StringTokenizer;

public class CommaSeperatedParsing {

 public static void main(String[] args) {

  // Create a String or pass any String containing comma
  // This utility will separate the String using split method. 
  String commaSeperatedString = "Name = Value,First Name = Jonty," +
    "Last Name = Magicman,UserName = Jontymagicman," +
    "Email = Jonty@Magic.com" ;

  System.out.println("Method 1 : Using String class split() method ... ");
  System.out.println();
  // String class has a method called as split method
  // this method takes in a regular expression and based
  // on the expression returns a array containing the 
  // strings 
  String[] output = commaSeperatedString.split(",");

  // using a for loop to print the parsed string to
  // console
  for(int i = 0; i < output.length; i++)
  {   
   System.out.println(output[i]);
  }

  System.out.println();
  System.out.println("Method 2 : Using StringTokenizer class  ... ");
  System.out.println();

  // Pass the String to the StringTokenizer class which will
  // break it into tokens separated by spaces.
  StringTokenizer stringTokenizer = 
    new StringTokenizer(commaSeperatedString , ",");

  // Applying while loop over the condition (till StringTokenizer
  // has no more elements left which are seperated by tokens.
  while(stringTokenizer.hasMoreElements())
  {
   // StringTokenizer has nextElement method which gets
   // us the next string in the class.
   System.out.println(stringTokenizer.nextElement());
  }


 }

}


Output of the program : 


 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot