java對字符串處理功能強大,以下是本人實際開發中用到的一些總結:
package org.bulktree.test; import java.util.StringTokenizer; /** *//** * * @author bulktree Email: [email protected] * @date Jul 31, 2008 */ public class SplitTest { public static void main(String[] args) { SplitTest st = new SplitTest(); // st.splitTest01(); //st.splitTest02(); st.StringTokenizierTest(); } public void splitTest01() { String s = "01111:aa:哈哈"; /**//* * limit 該值用來限制返回數組中的元素個數 */ String[] s1 = s.split(":"); System.out.println(s1[0]); /**//* * -1表示如果為空也能區分出來 */ String[] s2 = s.split(":", -1); System.out.println(s2[0]); String[] s3 = s.split(":", 1); System.out.println(s3[0]); } public void splitTest02() { // “.”和“|”都是轉義字符,必須得加"\\" String s = "bulktree.oakertree.laoshulin"; String ss = "bulktree|oakertree|laoshulin"; String sss = "bulktree.oakertree|laoshulin"; String[] s1 = s.split("\\."); System.out.println(s1[0]); String[] s2 = ss.split("\\|"); System.out.println(s2[0]); /**//* * 如果有多個分隔符,可以用"|"作為連字符 */ String[] s3 = sss.split("\\.|\\|"); System.out.println(s3[1]); } /**//* * 構造字符串的StringTokenizer對象測試 */ public void StringTokenizierTest() { String s = "I am a student,bulktree"; StringTokenizer str = new StringTokenizer(s); // 返回nextToken方法被調用的次數,分隔符的數量 System.out.println(str.countTokens()); // 是否有分隔符 while(str.hasMoreTokens()) { System.out.println(str.nextToken()); } } }