2015年10月2日 星期五

StringBuilder 用法


import java.io.PrintWriter;
import java.util.StringTokenizer;

public class StringDemo {
    public static void main(String[] args){
        
        //StringBuilder 範例
        StringBuilder sb = new StringBuilder(500);
        
        sb.append(", this is a good day!");
        sb.insert(0,"Today is Friday!");
        for (int i = 1; i< 11 ; i++){
            sb.append(i).append("    ");
        }
        sb.append("] times");
        System.out.println(sb.toString());
        System.out.println();
        
        //String Methods 範例
        PrintWriter pw = new PrintWriter(System.out, true);
        String tc01 = "It was the best of times";
        String tc02 = "It was the worst of times";
        
        if (tc01.equals(tc02)){
            pw.println("Strings match...");
        }
        if (tc01.contains("It was")){
            pw.println("It was found");
        }
        String temp = tc02.replace("w", "zw");
        pw.println(temp);
        pw.println(tc02.substring(5, 12));
         pw.println();
         
        //String Split 範例
        String shirts = "Blue Shirt, Red Shirt, Black Shirt, Maroon Shirt";
        
        String[] results = shirts.split(", ");
        for (String shirtStr:results){
            pw.println(shirtStr);
        }
         pw.println();
         
        //Tokenizer 範例
        StringTokenizer st = new StringTokenizer(shirts, ", ");
        while(st.hasMoreTokens()){
            pw.println(st.nextToken());
        }
    }
}