Java用split分割含一個或多個空格的字符串案例
使用正則表達(dá)式:
1.String的split方法支持正則表達(dá)式;
2.正則表達(dá)式\s表示匹配任何空白字符,+表示匹配一次或多次。
比如待分割字符串為:
String str = "the sky is blue";
分割函數(shù)為:
public static String[] flipping(String str){ String[] string = str.split("\\s+");//分割一個或多個空格 //String[] string = str.split(" ");//僅分割一個空格 return string; }
補(bǔ)充知識:Java中split()函數(shù)的用法及一些注意細(xì)節(jié)
String.split("要切割的準(zhǔn)側(cè)")返回的是一個String[ ]的首地址;String.split("要切割的準(zhǔn)側(cè)").length 返回的是這個String被切割后的子字符串的個數(shù)(即被切割成了幾個段);String.split(""),此時,切割后的第一個段是空字符串。代碼如下:
package Demo; public class DemoSplit { public static void main(String[] args) { test(); } public static void test(){ String s="a,b,c,d,e"; String temp[]; temp=s.split(",");//String用split切割后,返回的是一個String數(shù)組。 System.out.println("temp==="+temp);//System.out.print(s.split("要切割的準(zhǔn)則"))返回的是字符串?dāng)?shù)組的首地址 System.out.println("之后的長度:"+temp.length); System.out.println("切割后,子段的內(nèi)容為:"); for(int i=0;i<temp.length;i++){ System.out.println(temp[i]); } String temp1[]; temp1=s.split(""); System.out.println("temp1==="+temp1);//System.out.print(s.split("要切割的準(zhǔn)則"))返回的是字符串?dāng)?shù)組的首地址 System.out.println("之后的長度:"+temp1.length); System.out.println("切割后,子段的內(nèi)容為:"); for(int i=0;i<temp1.length;i++){ System.out.println(temp1[i]); } } }
運(yùn)行結(jié)果為:
以上這篇Java用split分割含一個或多個空格的字符串案例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java ThreadPoolExecutor的參數(shù)深入理解
這篇文章主要介紹了Java ThreadPoolExecutor的參數(shù)深入理解的相關(guān)資料,需要的朋友可以參考下2017-03-03玩轉(zhuǎn)spring boot 結(jié)合AngularJs和JDBC(4)
玩轉(zhuǎn)spring boot,這篇文章主要介紹了結(jié)合AngularJs和JDBC,玩轉(zhuǎn)spring boot,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-01-01Java Scala實現(xiàn)數(shù)據(jù)庫增刪查改操作詳解
這篇文章主要介紹了Java Scala實現(xiàn)數(shù)據(jù)庫增刪查改操作,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-04-04Java實現(xiàn)Excel轉(zhuǎn)PDF的兩種方法詳解
使用具將Excel轉(zhuǎn)為PDF的方法有很多,在這里我給大家介紹兩種常用的方法:使用spire轉(zhuǎn)化PDF、使用jacob實現(xiàn)Excel轉(zhuǎn)PDF,分別應(yīng)對兩種不一樣的使用場景,需要的可以參考一下2022-01-01