FileDocCategorySizeDatePackage
StrTokDemo4b.javaAPI DocExample1595Thu Mar 25 20:50:22 GMT 2004None

StrTokDemo4b

public class StrTokDemo4b extends Object
Show using a StringTokenizer including getting the delimiters back

Fields Summary
public static final String
DELIM
The delimiter used between fields on input.
Constructors Summary
Methods Summary
public static voidmain(java.lang.String[] a)

		printResults("A|B|C|D", process("A|B|C|D"));
		printResults("A||C|D", process("A||C|D"));
		printResults("A|||D|E", process("A|||D|E"));
	
public static voidprintResults(java.lang.String input, java.lang.Object[] outputs)

		System.out.println("Input: " + input);
		for (int i=0; i<outputs.length; i++)
			System.out.println("Output " + i + " was: " + outputs[i]);
	
public static java.lang.String[]process(java.lang.String line)
Processes one String, returns it as an array of Strings


	           
	     
		// ArrayList is an array-like container that grows dynamically;
		// see the chapter on Java Collections.
		List results = new ArrayList();

		// Unless you ask StringTokenizer to give you the tokens,
		// it silently discards multiple null tokens.
		StringTokenizer st = new StringTokenizer(line, DELIM, true);

		int i = 0;
		// Stuff each token into the ArrayList
		while (st.hasMoreTokens()) {
			String s = st.nextToken();
			if (s.equals(DELIM)) {
				// Just ignore the "tokens" that consist of DELIM
				// But do insert something for consecutive delimiters
				if (results.size() < ++i)
					results.add(null);
				continue;
			}
			results.add(s);
		}

		// Make an Array just the right size, ask the
		// ArrayList to copy its data into it, and return it.
		String[] sResults = new String[results.size()];
		results.toArray(sResults);
		return sResults;