使用正則表達式:
1.String的split方法支持正則表達式;
2.正則表達式\s表示匹配任何空白字符,+表示匹配一次或多次。
比如待分割字符串為:
String str = "the sky is blue";
分割函數為:
1
2
3
4
5
|
public static String[] flipping(String str){ //String[] string = str.split(" ");//僅分割一個空格 return string; } |
補充知識:Java中split()函數的用法及一些注意細節
String.split("要切割的準側")返回的是一個String[ ]的首地址;String.split("要切割的準側").length 返回的是這個String被切割后的子字符串的個數(即被切割成了幾個段);String.split(""),此時,切割后的第一個段是空字符串。代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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分割含一個或多個空格的字符串案例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/jkllb123/article/details/81474912