Java中split的用法小結

來源:互聯網
上載者:User

split(" ")和split("")的區別 。 

  • split(" "),""之間有空格

String s = "The rain in Spain falls mainly in the plain.";// ""之間有空格,在每個空白字元處進行分解。String [] ss = s.split(" ");System.out.println("[ss[0] ="+ss[0]+"]");System.out.println("[");for (String string : ss) {System.out.println(string);}System.out.println("]");

程式效果 : 
[ss[0] =The] 
[ 
The 
rain 
in 
Spain 
falls 
mainly 
in 
the 
plain. 
] 

================================================ 

  • split(""),""之間無空格
String s = "The rain in Spain falls mainly in the plain.";// ""之間沒有空格。String [] ss = s.split("");---->此處可以將字串,一個一個拆分成打個字母,但是包孕空格,如果不需要空格的話,自己寫個法子,將空格刪掉就行了!System.out.println("[ss[0] ="+ss[0]+"]");System.out.println("[");for (String string : ss) {System.out.println(string);}System.out.println("]");

程式效果 : 

[ss[0] =][The rain in Spain falls mainly in the plain.]

  今天再拆分IP地址的時候遇到的!以前還真的沒有深入 的鑽研 過!哎..... 

  雖然網上也有解釋 ,但是自己還是總結下,這樣才幹 使自己的東西! 

  • 採納 split(".")進行拆分:
String ip = "127.0.0.1";String [] s = ip.split(".");<-----逝世活出不來成果for (String string : s) {System.out.println(string);}
  • 尋找材料 後,改善split的參數設定
  • 採納 split("//.")進行拆分:
     String ip = "127.0.0.1"; //     String [] s = ip.split(".");String [] s = ip.split("//.");for (String string : s) {System.out.println(string);}
程式運行效果:127001
  • 原因分析 :split(String regex) 裡面不是普通的string,是Regex,.有特別 的含義

  • 經驗分享:
  • 1、分隔字元為“.”(無輸出),“|”(不能得到正確 效果 )逸出字元時,“*”,“+”時出錯拋出異常,都必須 在前面加必須 得加"//",如split(//|);
  • 2、如果用"/"作為分隔,就得寫成這樣:String.split("////"),因為在Java中是用"//"來表現 "/"的,字串得寫成這樣:String Str="a//b//c";
  • 逸出字元,必須 得加"//";
  • 3、如果在一個字串中有多個分隔字元,可以用"|"作為連字號,比如:String str="Java string-split#test",可以用Str.split(" |-|#")把每個字串離開 ;

聯繫我們

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