/* * @(#) TestStringTokenizer.java * in package net.outinn.james.codebase.java.util * by James Fancy * on 2003-9-27 */ package net.outinn.james.codebase.java.util; import java.util.StringTokenizer; /** * TestStringTokenizer 類給出了三個樣本,示範了 StringTokenizer 類的常見用法。 * <p>該範例程式碼運行結果</p> * <blockquote><pre> * --------- TEST1 --------- * name * telephone * fax * email * address * --------- TEST2 --------- * name * telephone * fax * email * address * --------- TEST3 --------- * The * file * Good Java Code.txt * is * in * dir * My Documents * of * volume * Doc Volume * </pre></blockquote> * @author James Fancy * on 2003-9-27 9:12:34 * @see java.util.StringTokenizer */public final class StringTokenizerDemo { private final String source1 = "name|telephone,fax;email.address"; private final String source3 = "The file /"Good Java Code.txt/" is in" + " dir /"My Documents/" of volume /"Doc Volume/""; private final String delim1 = ";,.|"; // 包含分號、逗號、句點、豎址分隔字元 private final String delim2 = " /""; // 包含空格、引號 private final String delim3 = "/""; // 僅包含引號private void printSeparater(String title) { System.out.println("--------- " + title + " ---------"); }/** * 示範 StringTokenizer 最常用的用法,使用 StringTokenizer(String, String) * 構造 Tokenizer。 * @see java.util.StringTokenizer#StringTokenizer(String, String) * @see java.util.StringTokenizer#hasMoreTokens() * @see java.util.StringTokenizer#nextToken() */ public void test1() { this.printSeparater("TEST1"); StringTokenizer tokenizer; tokenizer = new StringTokenizer(source1, delim1); while (tokenizer.hasMoreTokens()) { System.out.println(tokenizer.nextToken()); } }/** * 示範 StringTokenizer 的 nextToken(String) 用法 * @see java.util.StringTokenizer#StringTokenizer(String) * @see java.util.StringTokenizer#hasMoreTokens() * @see java.util.StringTokenizer#nextToken(String) */ public void test2() { this.printSeparater("TEST2"); StringTokenizer tokenizer = new StringTokenizer(source1); while (tokenizer.hasMoreTokens()) { System.out.println(tokenizer.nextToken(delim1)); } }/** * 一個較綜合的樣本,它拆分一句話,將每個單詞拆分出來,其中, * 被雙引號包含的若干單詞被處理為一個單詞輸出。 * @see java.util.StringTokenizer#StringTokenizer(String, String, boolean) * @see java.util.StringTokenizer#hasMoreTokens() * @see java.util.StringTokenizer#nextToken() * @see java.util.StringTokenizer#nextToken(String) */ public void test3() { this.printSeparater("TEST3"); String delim = delim2; String word; boolean begin = false; StringTokenizer tokenizer = new StringTokenizer(source3, delim, true); while (tokenizer.hasMoreTokens()) { word = tokenizer.nextToken(delim); if (word.equals("/"")) { if (begin) { delim = delim2; begin = false; } else { delim = delim3; begin = true; } } else if (!word.equals(" ")) { System.out.println(word); } } }/** * 這個 main 方法輸出預設的測試結果。 * @param args 命令列參數 */ public final static void main(String[] args) { StringTokenizerDemo demo = new StringTokenizerDemo(); demo.test1(); demo.test2(); demo.test3(); } }