)java關於split分割字串,空的字串不能得到的問題

來源:互聯網
上載者:User
class T {   
  public static void main(String args[]) {   
    String num[] = new String[11];   
    String sLine = "101494|360103660318444|2008/06/17|周潤英|1292.0|3085.76|2778.28|912.91|106.0|||";   
    num = sLine.split("\\|");   
    int row = 1;   
    for (String s : num) {   
      System.out.println(row+++"="+s);   
    }   
  }   

最有有三個|||,運行結果為
1=101494
2=360103660318444
3=2008/06/17
4=周潤英
5=1292.0
6=3085.76
7=2778.28
8=912.91
9=106.0

查看API,有一個public String[] split(String regex, int limit); 

limit 參數控制應用模式的次數,從而影響結果數組的長度。

如果限制 n 大於零,那麼模式至多應用 n> - 1 次,數組的長度不大於 n,並且數組的最後條目將包含除最後的匹配定界符之外的所有輸入。

如果 n 非正,那麼將應用模式的次數不受限制,並且數組可以為任意長度。

如果 n 為零,那麼應用模式的次數不受限制,數組可以為任意長度,並且將丟棄尾部Null 字元串。 

修改代碼為 class T {   
  public static void main(String args[]) {   
    String num[] = new String[11];   
    String sLine = "101494|360103660318444|2008/06/17|周潤英|1292.0|3085.76|2778.28|912.91|106.0|||";   
    num = sLine.split("\\|",-1); // 這裡使用-1作為參數   
    int row = 1;   
    for (String s : num) {   
      System.out.println(row+++"="+s);   
    }   
  }   
}  

運行結果為
1=101494
2=360103660318444
3=2008/06/17
4=周潤英
5=1292.0
6=3085.76
7=2778.28
8=912.91
9=106.0
10=
11=
12=

結果正常

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.