1.StringBuffer 與 StringBuilder
字串需一直變動使用String每變動一次都會產生新的物件,會浪費記憶體,這時就要用StringBuffer與StringBuiler,
StringBuiler不能使用在多執行序。
StringBuffer b = new StringBuffer("12345"); // 創立文字 b.append("6789"); // 加入文字 System.out.println(b); b.delete(2, 4); // 刪除文字 (開始,結束) System.out.println(b); b.insert(3, "34"); // 增加文字 (開始,插入值) System.out.println(b); b.replace(1, 5, "二三四"); // 取代(開始,結束,值) 只會取代開始與結束中間的值 System.out.println(b); b.reverse(); // 顛倒 System.out.println(b); b.reverse(); // 顛倒 String a = new String(b); String c = a.replaceAll("二三四", "234"); // 正規法取代 System.out.println(c); 執行結果: 1256789 125346789 1二三四6789 9876四三二1 12346789
2.規則表示法
例1:
String s = "123456789"; System.out.println(s.matches("[0-9]")); // false (只比對一位數 s="1"才會是true) System.out.println(s.matches("[0-9]+")); // ture (+至少出現1次以上的數字) System.out.println(s.matches("[0-9]*")); // ture (*0或多次) System.out.println(s.matches("[0-9]{9}")); // ture (剛好出現9個) System.out.println(s.matches("[0-9]{3,}")); // ture (3個以上) System.out.println(s.matches("[0-9]{3,8}")); // false (3-8個) String b = "123"; System.out.println(b.matches("1[^123]3")); // false (^是不包含) System.out.println(b.matches("1[123]3")); // true
System.out.println(b.matches("1([123])+3")); // true ()為群組// 手機號碼檢查 String b = "0935751111"; System.out.println(b.matches("0[0-9]{9}")); // true // Eamil String b = "leeeee@yahoo.com.tw"; String b = "leeeee@yahoo.com.tw"; System.out.println(b.matches("[A-Za-z_]{1}[A-Za-z1-9_\\.]*@[A-Za-z1-9_]{1}[A-Za-z1-9_\\.]*")); // true // 簡易身分證 String b = "C222990912"; System.out.println(b.matches("[A-Z]{1}[12]{1}[0-9]{8}")); // true
3.split (explode)
String a = "1,2,3,4,5"; String[] c = a.split(","); for(String i:c){ System.out.print(i); // 12345 }