Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

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 : 


 
 
© 2021 Learn Java by Examples Template by Hubberspot