java split函數分割字符串
覺得有用的話,歡迎一起討論相互學習~




- java split("sign")函數,可以按照 sign中標注的分割符對字符串進行分割,分割為String[]字符串數組。在字符串操作中十分常用!
示例
String a = "1,2,3,4,4,5";
String[] b = a.split(",");
for (int i = 0; i < b.length; i++) {
System.out.println(i+" "+b[i]);
}
// 0 1
// 1 2
// 2 3
// 3 4
// 4 4
// 5 5
- 但是需要注意
"."和"|"都是轉義字符,因此需要在前面使用"\\"
加以區分成為"\\."和"\\|"
- 並且,如果有多個分割符,可以使用"|"加以區分,即類似split(",|:")
public class test {
public static void main(String[] args) {
String a="123.csv";
System.out.println(a.split("\\.")[0]);
String b="123|csv";
System.out.println(b.split("\\|")[0]);
String c="123,csv:321";
System.out.println(c.split(",|:")[0]+c.split(",|:")[1]+c.split(",|:")[2]);
}
}
//123
//123
//123csv321