本文目錄一覽:
java中split怎麼用?
split函數中的參數是正則表達式,當然也可以是普通字符
一普通字符:
String ip = “192.168.1.1”;
String a[] = ip.split(“\\.”);
for(int i=0;ia.length;i++){
System.out.println(a[i]);
}
String ipName = ip.replaceAll(“\\.”, “-“);
System.out.println(ipName);
String[] ipArr = ipName.split(“-“);
for(int i=0;iipArr.length;i++){
System.out.println(ipArr[i]);
}
Java的split()是怎麼拆分字符串的?
java拆分字符串使用string類的spilt方法,針對某個分隔符來分割一個字符串,示例如下:
public class StringSplit {
public static void main(String[] args) {
String sourceStr = “1,2,3,4,5”;//一個字符串
String[] sourceStrArray = sourceStr.split(“,”);//分割出來的字符數組
for (int i = 0; i sourceStrArray.length; i++) {
System.out.println(sourceStrArray[i]);
}
// 最多分割出3個字符串
int maxSplit = 3;
sourceStrArray = sourceStr.split(“,”, maxSplit);
for (int i = 0; i sourceStrArray.length; i++) {
System.out.println(sourceStrArray[i]);
}
}
}
輸出結果為:
2
4
1
3,4,5
java 中的split 方法
注意sun給出的split說明就可以理解了
對於a = “abcd”.split(“”);
其實默認調用的是split(“”,0);
查找說明,限制為零,忽略結尾;那麼這樣我們就可以理解,由於採用的是split(“”)所以在”abcd”中應該是””,a,b,c,d,””;結尾被忽略的。所以最後的輸出應該是
–0
a–1
b–2
c–3
d–4
split
public String[] split(String regex,
int limit)根據匹配給定的正則表達式來拆分此字符串。
此方法返回的數組包含此字符串的子字符串,每個子字符串都由另一個匹配給定表達式的子字符串終止,或者由此字符串末尾終止。數組中的子字符串按它們在此字符串中出現的順序排列。如果表達式不匹配輸入的任何部分,那麼所得數組只具有一個元素,即此字符串。
limit 參數控制模式應用的次數,因此影響所得數組的長度。如果該限制 n 大於 0,則模式將被最多應用 n – 1 次,數組的長度將不會大於 n,而且數組的最後一項將包含所有超出最後匹配的定界符的輸入。如果 n 為非正,那麼模式將被應用儘可能多的次數,而且數組可以是任何長度。如果 n 為 0,那麼模式將被應用儘可能多的次數,數組可以是任何長度,並且結尾空字符串將被丟棄。
例如,字符串 “boo:and:foo” 使用這些參數可生成以下結果:
Regex Limit 結果
: 2 { “boo”, “and:foo” }
: 5 { “boo”, “and”, “foo” }
: -2 { “boo”, “and”, “foo” }
o 5 { “b”, “”, “:and:f”, “”, “” }
o -2 { “b”, “”, “:and:f”, “”, “” }
o 0 { “b”, “”, “:and:f” }
調用此方法的 str.split(regex, n) 形式與以下表達式產生的結果完全相同:
Pattern.compile(regex).split(str, n)
參數:
regex – 定界正則表達式
limit – 結果閾值,如上所述
返回:
字符串數組,它是根據給定正則表達式的匹配拆分此字符串確定的
拋出:
PatternSyntaxException – 如果正則表達式的語法無效
從以下版本開始:
1.4
另請參見:
Pattern
——————————————————————————–
split
public String[] split(String regex)根據給定正則表達式的匹配拆分此字符串。
該方法的作用就像是使用給定的表達式和限制參數 0 來調用兩參數 split 方法。因此,所得數組中不包括結尾空字符串。
例如,字符串 “boo:and:foo” 使用這些表達式可生成以下結果:
Regex 結果
: { “boo”, “and”, “foo” }
o { “b”, “”, “:and:f” }
參數:
regex – 定界正則表達式
返回:
字符串數組,它是根據給定正則表達式的匹配拆分此字符串確定的
拋出:
PatternSyntaxException – 如果正則表達式的語法無效
從以下版本開始:
1.4
另請參見:
Pattern
Java split方法
java中String的split方法有兩個,
split(String regex) 根據給定正則表達式的匹配拆分此字符串。例如:將下列字符串以“a”分割,
public String[] split(String regex,
int limit)
參數:regex – 定界正則表達式
limit – 結果閾值
例如下:
其中:limit來限制被分割後數組的元素個數;
java中的split函數
那是字符串分割的方法
比如有個字符串是這樣的
string
str
=
“boo:and:foo”;
調用它的方法
str.split(“:”);意思是以“:”分割上面的字符串。返回一個字符串數組,數組裡面就是
{
“boo”,
“and”,
“foo”
}
原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/128848.html