java split 的一些用法注意点。

java split 的一些用法注意点。
import java.util.Arrays;


public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
        /**
         * public String[] split(String regex, int limit)
         * regex 是正则表达式
         * limit 是返回数组上限的临界值, 
         *       如果是负数,全部取,
         *       如果是0,取本身
         *       如果是n(1到可取的数大值),
         *        表示取前n个,boo:and:foo 时,以:split,n=2 ,结果为boo和 and:foo
         */
        String str="boo:and:foo";
        System.out.println(str);
        System.out.println(":\t \t"+Arrays.toString(str.split(":")));
        //:	 	[boo, and, foo]
        
        System.out.println(":\t2\t"+Arrays.toString(str.split(":",2)));
        //:	2	[boo, and:foo]
        
        System.out.println(":\t-1\t"+Arrays.toString(str.split(":",-1)));
        //:	-1	[boo, and, foo]
        
        System.out.println("0\t \t"+Arrays.toString(str.split("o")));
        //0	 	[b, , :and:f]
        
        System.out.println("o\t5\t"+Arrays.toString(str.split("o",5)));
        //o	5	[b, , :and:f, , ]
        
        System.out.println("o\t-1\t"+Arrays.toString(str.split("o",-1)));
        //o	-1	[b, , :and:f, , ]
        
        System.out.println("o\to\t"+Arrays.toString(str.split("0",0)));
        //o	o	[boo:and:foo]
        
        System.out.println("o+\t \t"+Arrays.toString(str.split("o+")));
        //o+	 	[b, :and:f]

        //经常会遇到web的get参数中,经常会遇到这个要情况,key 为a ,值为abc2=222,时
        //可以这样split
        String str2="a=abc2=222";
        System.out.println();
        System.out.println(str2);
        System.out.println("=\t2\t"+Arrays.toString(str2.split("=",2)));
        //=	2	[a, abc2=222]
        
        //当最后还一个值还包括所要split分隔符时,
        //split(regex) 和 split(regex,-1)会有所不同。
        // split(regex) 忽略掉最后一个,split(regex,-1) 会全部分拆
        String str3="a,b,c,d,";
        System.out.println();
        System.out.println(str3);
        System.out.println(",\t \t"+Arrays.toString(str3.split(",")));
        //,	 	[a, b, c, d]
        
        System.out.println(",\t-1\t"+Arrays.toString(str3.split(",",-1)));
        //,	-1	[a, b, c, d, ]

	}

}


结果:
boo:and:foo
: [boo, and, foo]
: 2 [boo, and:foo]
: -1 [boo, and, foo]
0 [b, , :and:f]
o 5 [b, , :and:f, , ]
o -1 [b, , :and:f, , ]
o o [boo:and:foo]
o+ [b, :and:f]

a=abc2=222
= 2 [a, abc2=222]

a,b,c,d,
, [a, b, c, d]
, -1 [a, b, c, d, ]

猜你喜欢

转载自huangzhir.iteye.com/blog/1880544