Stringtokenizer That Works with Empty Strings

 import java.util.*;import java.io.*;class Class1	{	static Vector split(String string,String delimiter)		{ //StringTokenizer that works with empty strings		boolean wasDelimiter=true;		String token=null;		Vector vector=new Vector();		if(string!=null)			for(StringTokenizer stringTokenizer=new StringTokenizer(string,delimiter,true);stringTokenizer.hasMoreTokens();)				{				if((token=stringTokenizer.nextToken()).equals(delimiter))					{					token=wasDelimiter?"":null;					wasDelimiter=true;					}					else wasDelimiter=false;				if(token!=null)					vector.addElement(token);        			}		return vector;		}	static boolean test(String original,String delimiter)		{ // split, then reconstruct the original string		Vector token=split(original,delimiter);		String reconstructed="";		if(original!=null)			{			for(int i=0;i0)					reconstructed+=delimiter;				reconstructed+=(String)token.elementAt(i);				}    			if(original.endsWith(delimiter)) // allow a trailing delimiter			reconstructed+=delimiter;			}		System.out.println("     original ""+original+""");		System.out.println("reconstructed ""+reconstructed+""");		System.out.println(token.size()+" tokens");		return original==null?true:original.equals(reconstructed);		}	public static void main(String[] argument)		{		BufferedReader in=new BufferedReader(new InputStreamReader(System.in));		for(String string=null;;)			{			System.out.println();			System.out.println("enter string (e.g. a,,b");			try { string=in.readLine(); }			catch(IOException e) { System.out.println(e); System.exit(1); }			if(!test(string,","))				System.err.println("fail!");			if(string==null)				return;			}		}	}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: