Java用split分割含一個或多個空格的字符串案例
使用正則表達式:
1.String的split方法支持正則表達式;
2.正則表達式s表示匹配任何空白字符,+表示匹配一次或多次。
比如待分割字符串為:
String str = 'the sky is blue';
分割函數為:
public static String[] flipping(String str){ String[] string = str.split('s+');//分割一個或多個空格 //String[] string = str.split(' ');//僅分割一個空格 return string; }
補充知識:Java中split()函數的用法及一些注意細節
String.split('要切割的準側')返回的是一個String[ ]的首地址;String.split('要切割的準側').length 返回的是這個String被切割后的子字符串的個數(即被切割成了幾個段);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數組。 System.out.println('temp==='+temp);//System.out.print(s.split('要切割的準則'))返回的是字符串數組的首地址 System.out.println('之后的長度:'+temp.length); System.out.println('切割后,子段的內容為:'); 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('要切割的準則'))返回的是字符串數組的首地址 System.out.println('之后的長度:'+temp1.length); System.out.println('切割后,子段的內容為:'); for(int i=0;i<temp1.length;i++){ System.out.println(temp1[i]); } }}
運行結果為:
以上這篇Java用split分割含一個或多個空格的字符串案例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
1. vue-drag-chart 拖動/縮放圖表組件的實例代碼2. vue使用moment如何將時間戳轉為標準日期時間格式3. Android studio 解決logcat無過濾工具欄的操作4. 什么是Python變量作用域5. js select支持手動輸入功能實現代碼6. PHP正則表達式函數preg_replace用法實例分析7. Android Studio3.6.+ 插件搜索不到終極解決方案(圖文詳解)8. bootstrap select2 動態從后臺Ajax動態獲取數據的代碼9. Android 實現徹底退出自己APP 并殺掉所有相關的進程10. 一個 2 年 Android 開發者的 18 條忠告
