java中的String字符串属于常量类,使用的场合比较多。其中字符串的剪切使用更是频繁,split是一种很好,也是使用很频繁的字符串剪切方式,对于以"."和"|"为分隔符的字符串,用split剪切时需要转义一下,否则无效。注意代码中的"\\."和"\\|"
java.lang.String
split方法:将一个字符串分割为子字符串,然后将结果作为字符串数组返回。
stringObj.split(regex,[limit])
stringObj:必选项。要被分解的 String 对象或文字。该对象不会被 split 方法修改。
regex:必选项。定界正则表达式。
limit:可选项。该值用来限制返回数组中的元素个数。如果不选择默认为0,此时结果数组返回全部分割子串,其中不包括结尾空字符串。
返回:字符串数组,根据给定正则表达式的匹配来拆分此字符串,从而生成此数组。
抛出PatternSyntaxException:如果正则表达式的语法无效
从以下版本开始:1.4
说明:split 方法的结果是一个字符串数组,在 stingObj 中每个出现 regex的位置都要进行分解,与表达式Pattern.compile(regex).split
(str, limit)的结果完全相同。
 
示例1:
 //start
 String test = "This is a
simple example!";
 String[] arrtest =
test.split(" ");
 for(int i = 0; i
< arrtest.length;
i++){
     System.out.println(arrtest[i]);
 }
 //end
输出:
This
is
a
simple
example!
 
示例2:
 String test = "This is a
simple example!";
 String[] arrtest =
test.split(" ",0);
 for(int i = 0; i
< arrtest.length;
i++){
     System.out.println(arrtest[i]);
 }
输出:
This
is
a
simple
example!
 
示例3:
   String
test = "This is a simple example!";
 String[] arrtest =
test.split(" ",3);
 for(int i = 0; i
< arrtest.length;
i++){
     System.out.println(arrtest[i]);
 }
输出:
This
is
a simple example!
 
示例4:
 String test = "This is a
simple example!";
 String[] arrtest =
test.split(" ",100);
 for(int i = 0; i
< arrtest.length;
i++){
     System.out.println(arrtest[i]);
 }
输出:
This
is
a
simple
example!
 
再看示例5:
 String test =
"This|is|a|simple|example!";
 String[] arrtest =
test.split("|");
 for(int i = 0; i
< arrtest.length;
i++){
     System.out.println(arrtest[i]);
 }
输出:
T
h
i
s
|
i
s
|
a
|
s
i
m
p
l
e
|
e
x
a
m
p
l
e!
 
     此时就出问题了,以上代码没有按照我预想的输出结果!
     我们在来看看regex的解释——定界正则表达。原来是正则表达式在作怪,像|、[、/、.、*、?、{等都是正则表达式里的特殊字符,它们在正则表达式中有其特殊的意义。此时必须用转义字符来处理(请注意这里是用//来转义)。
 
示例5改正:
 String test =
"This|is|a|simple|example!";
 String[] arrtest =
test.split("//|");
 for(int i = 0; i
< arrtest.length;
i++){
     System.out.println(arrtest[i]);
 }
输出:
This
is
a
simple
example!
    
       另外如果出现多个分隔符可以有“|”来作连字符连接。
示例6:
 String test = "You and
me,from one world!";
 String[] arrtest =
test.split(" |,");
 for(int i = 0; i
< arrtest.length;
i++){
     System.out.println(arrtest[i]);
 }
输出:
You
and
me
from
oneworld!
另外像matches(String
regex),replaceAll(String regex,String
replacement)这类函数的处理都要用到正则表达。
							
		 
						
		加载中,请稍候......