Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Feb 24, 2000

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;
			}
		}
	}
Ray Tayek
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date