Stringtokenizer That Works with Empty Strings

Stringtokenizer That Works with Empty Strings

 import java.util.*;import*;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(;		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;			}		}	}
See also  Using Consumer Trust to Help Build Brands On Major Social Platforms

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist