前言:
1,split
2,substring / StringUtils.substring
3,StringUtils.substringBefore / StringUtils.substringBeforeLast
4,StringUtils.substringAfter / StringUtils.substringAfterLast
5,StringUtils.substringBetween
正文:
1,split
將正則傳入split()。返回的是一個字符串數組類型。不過通過這種方式截取會有很大的性能損耗,因為分析正則非常耗時。
注:
下標不能超過數組長度(strs.length),不然會報錯;
Java的split方法是把字符串末尾的空字符全部舍棄的,這點要注意;
分割符為“.”和“|”(轉義字符)的話,必須得加"\\",不加的話會分割成單個字符;
如果在一個字符串中有多個分隔符,可以用“|”作為連字符,比如:“a=1 and b=2 or c=3”,把三個都分隔出來,可以用String.split("and|or");
//按逗號分割字符串為數組 String str = "a,b,c"; String[] strs = str.split(","); System.out.println(strs[0]); //得到a
2,substring / StringUtils.substring
str.substring(2, 4) :索引值從0開始,該式子代表從索引2截取到索引4(不包含索引4,實際截取的是索引2和3)
str.substring(2) :從索引2截取到末尾(包含末尾值)
str.substring(-2) :從右往左開始數
注:截取范圍超出字符串位數時會報錯,所以要用str.length()先獲取一下字符長度
String str = "abcdefg"; System.out.println(str.substring(2, 4)); //得到cd
StringUtils.substring(str, 2, 4):同上
3,StringUtils.substringBefore / StringUtils.substringBeforeLast
StringUtils.substringBefore(str, char) :獲取第一個指定字符前面的字符(指定字符可以是一個或多個字符)
String result = StringUtils.substringBefore("123e45ee6", "e"); System.out.println(result); //得到123
StringUtils.substringBeforeLast(str, char) :獲取最后一個指定字符前面的字符
String result = StringUtils.substringBeforeLast("123e45ee6", "e"); System.out.println(result); //得到123e45e
4,StringUtils.substringAfter / StringUtils.substringAfterLast
StringUtils.substringBefore(str, char) :獲取第一個指定字符后面的字符
String result = StringUtils.substringAfter("123e45ee6", "e"); System.out.println(result); //得到45ee6
StringUtils.substringAfterLast(str, char) :獲取最后一個指定字符后面的字符
String result = StringUtils.substringAfter("123e45ee6", "e"); System.out.println(result); //得到6
5,StringUtils.substringBetween
StringUtils.substringBetween(str,char1, char2) : 獲取char1和char2中間的字符
String result = StringUtils.substringAfter("123e45ee6", "12", "e"); System.out.println(result); //得到3
參考博客:
1,java 字符串截取的幾種方式 - 奮斗的小火車 - CSDN博客
https://blog.csdn.net/qq_27603235/article/details/51604584
2,StringUtils工具類常用方法匯總2(截取、去除空白、包含、查詢索引) - |一只想飛的豬| - 博客園
https://www.cnblogs.com/guiblog/p/7986410.html
3,java中split的坑,用的時候一定要小心 - 孫琛斌的專欄 - CSDN博客
https://blog.csdn.net/sun5769675/article/details/50204591