Java String类的split方法使用

来源:互联网 发布:淘宝网服务中心电话 编辑:程序博客网 时间:2024/03/29 17:38

split 方法
将一个字符串分割为子字符串,然后将结果作为字符串数组返回。
stringObj.split([separator,[limit]])
参数
stringObj 
必选项。要被分解的 String 对象或文字。该对象不会被 split 方法修改。
separator 
可选项。字符串或 正则表达式 对象,它标识了分隔字符串时使用的是一个还是多个字符。如果忽

略该选项,返回包含整个字符串的单一元素数组。 
limit
可选项。该值用来限制返回数组中的元素个数。

说明
split 方法的结果是一个字符串数组,在 stingObj 中每个出现 separator 的位置都要进行分解

。separator 不作为任何数组元素的部分返回。

示例1:

java 代码
 
  1. public class SplitDemo {   
  2.  public static String[] ss=new String[20];   
  3.  public SplitDemo() {   
  4.       
  5.      String s = "The rain in Spain falls mainly in the plain.";   
  6.      // 在每个空格字符处进行分解。   
  7.      ss = s.split(" ");        
  8.  }    
  9.  public static void main(String[] args) {   
  10.     
  11.   SplitDemo demo=new SplitDemo();   
  12.   for(int i=0;i<ss.length;i++)   
  13.   System.out.println(ss[i]);   
  14.  }   
  15.   
  16. }   
  17.   

程序结果:
The
rain
in
Spain
falls
mainly
in
the
plain.


示例2:

java 代码
 
  1. public class SplitDemo {   
  2.  public static String[] ss=new String[20];   
  3.  public SplitDemo() {   
  4.       
  5.      String s = "The rain in Spain falls mainly in the plain.";   
  6.      // 在每个空格字符处进行分解。   
  7.      ss = s.split(" ",2);       
  8.  }    
  9.  public static void main(String[] args) {   
  10.   SplitDemo demo=new SplitDemo();   
  11.   for(int i=0;i<ss.length;i++)   
  12.   System.out.println(ss[i]);   
  13.  }   
  14.   
  15. }   


程序结果:
The
rain in Spain falls mainly in the plain.

示例3:

java 代码
 
  1. public class SplitDemo {   
  2.  public static String[] ss=new String[20];   
  3.  public SplitDemo() {   
  4.       
  5.      String s = "The rain in Spain falls mainly in the plain.";   
  6.      // 在每个空格字符处进行分解。   
  7.      ss = s.split(" ",20);       
  8.  }    
  9.  public static void main(String[] args) {   
  10.   SplitDemo demo=new SplitDemo();   
  11.   for(int i=0;i<ss.length;i++)   
  12.   System.out.println(ss[i]);   
  13.  }   
  14.   
  15. }   


程序结果:
The
rain
in
Spain
falls
mainly
in
the

plain.






JAVA中也有split()方法,使用的时候要注意一个细节:

例如,有这样的字符串需要分割:

    String str = "a|b|c"; 

    String[] strArr = str.split("|");

得到结果并不是:

    strArr[0] = "a";

    strArr[1] = "b";

    strArr[2] = "c";

 

正确的使用方法是:

1、如果用“.”作为分隔的话,必须是如下写法:String.split("\\.")

2、如果用“|”作为分隔的话,必须是如下写法:String.split("\\|")

“.”和“|”都是转义字符,必须得加"\\";
3、如果在一个字符串中有多个分隔符,可以用“|”作为连字符,比如:“a=1 and b =2 or c=3”,把三个都分隔出来,可以用String.split("and|or");

 


0 0