split方法————>java中

來源:互聯網
上載者:User

java.lang包下有個String類的方法:split("separator"【,limit】),該方法返回一個數組

其中separator表示分隔字元,limit表示返回數組的元素個數

注意:
separator中如果有“.”和“|”逸出字元時前面必須加\\:
如果用“.”作為分隔的話,必須是如下寫法:String.split("\\."),這樣才能正確的分隔開,不能用String.split(".");
如果用“|”作為分隔的話,必須是如下寫法:String.split("\\|"),這樣才能正確的分隔開,不能用String.split("|");
如果在一個字串中有多個分隔字元,可以用“|”作為連字號,比如:“a=1 and b =2 or c=3”,把三個都分隔出來,可以用String.split("and|or");
limit分組時是對整個字串分組,分組後的元素包含原來String字串裡的所有字元!如下面的樣本2:

樣本1:

public class SplitDemo {
    public static String[] ss=new String[20];
    public SplitDemo() {
         String s = "The rain in Spain falls mainly in the plain.";
         // 在每個空白字元處進行分解。
         ss = s.split(" ");     
    }
    public static void main(String[] args) {
        SplitDemo demo=new SplitDemo();
        for(int i=0;i<ss.length;i++)
        System.out.println(ss[i]);
    }
}
程式結果:
The
rain
in
Spain
falls
mainly
in
the
plain

樣本2:

public class SplitDemo {
    public static String[] ss=new String[20];
    public SplitDemo() {
         String s = "The rain in Spain falls mainly in the plain.";
         ss = s.split(" ",2);    // 在每個空白字元處進行分解。
    }
    public static void main(String[] args) {
        SplitDemo demo=new SplitDemo();
        for(int i=0;i<ss.length;i++)
        System.out.println(ss[i]);
    }
}

程式結果:

The
rain in Spain falls mainly in the plain

樣本3:

public class SplitDemo3 {
    public static String[] ss = new String[20];
    public SplitDemo3() {
        String s = "The rain in Spain falls mainly in the plain.";
        ss = s.split(" ", 20);     // 在每個空白字元處進行分解
    }
    public static void main(String[] args) {
        SplitDemo3 demo = new SplitDemo3();
        for (int i = 0; i < ss.length; i++)
            System.out.println(ss[i]);
    }
}
程式結果:

The
rain
in
Spain
falls
mainly
in
the
plain.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.