dcsimg
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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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