Java用split分割含一個或多個空格的字符串案例
使用正則表達式:
1.String的split方法支持正則表達式;
2.正則表達式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; }
補充知識:Java中split()函數(shù)的用法及一些注意細節(jié)
String.split('要切割的準側(cè)')返回的是一個String[ ]的首地址;String.split('要切割的準側(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('要切割的準則'))返回的是字符串?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('要切割的準則'))返回的是字符串?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]); } }}
運行結(jié)果為:
以上這篇Java用split分割含一個或多個空格的字符串案例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. XML入門的常見問題(一)2. html小技巧之td,div標簽里內(nèi)容不換行3. PHP字符串前后字符或空格刪除方法介紹4. AspNetCore&MassTransit Courier實現(xiàn)分布式事務(wù)的詳細過程5. jsp cookie+session實現(xiàn)簡易自動登錄6. css進階學(xué)習(xí) 選擇符7. 將properties文件的配置設(shè)置為整個Web應(yīng)用的全局變量實現(xiàn)方法8. 解析原生JS getComputedStyle9. Echarts通過dataset數(shù)據(jù)集實現(xiàn)創(chuàng)建單軸散點圖10. nestjs實現(xiàn)圖形校驗和單點登錄的示例代碼
