在項目中經常會對String進行一些操作,除了一些開源框架中的StringUtils,我把在項目中經常要用的方法封裝成了一個StringUtil類,可供大家學習借鑑。
- EMPTY:返回一個空字符
- isNullString(String str):判斷是否是空字符串
- subStringBefore(String str,String separator):截取特定字符前面的字符串(不區分大小寫)
- subStringAfter(String str,String separator):截取特定字符後面的字符串(不區分大小寫)
- subStringAfterLastIgnoreCase(String str, String separator):截取特定字符後面的字符串(不區分大小寫)
- subStringBeforeLastIgnoreCase(String str,String separator):截取特定字符前面的字符串(不區分大小寫)
- singleQuotoAndEscape (String str):給字符串前後拼一個單引號,便於sql字符拼接
- escapeSqlLike(String str):用於拼接LIKE查詢,字符前後加一個%
- singleQuotoAndEscape(String[] strs):將數組的字符分割後加上單引號
- splitToList(String str,String separator):字符串根據分隔符轉換成List
- splitToListByUpStraight(String str):按豎線分隔轉成List
- replaceAllToEmpty(String str,String... stringsToReplace):在str把傳入的stringsToReplace替換爲空
- replaceAllTargetValue(String str, String targetValue, String... stringsToReplace):在str把傳入的stringsToReplace替換爲targetValue
- combineToString(Collection<String> coll, String seperator):將集合轉爲用 seperator連接的String字符串
- countMatches(String str,String sub):sub 在str中出現的次數
直接上代碼:
package com.java_foundation.util;
import org.junit.Assert;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @program: java_foundation
* @description: 字符串常用方法工具類
* @author: xiongbangwen <Email>[email protected]</Email>
* @create: 2020-05-29 11:05
**/
public class StringUtil {
public static final String EMPTY = "";
/*
* @Description: 判斷是否是空字符串
* @Param: [str]
* @return: boolean
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/5/29 13:58
*/
public static final boolean isNullString(String str){
return str == null || str.length() == 0 || str.trim().length() == 0;
}
/*
* @Description: 截取特定字符前面的字符串(不區分大小寫),regionMatches方法可控制是否區分
* 傳 'hello' 'l' 返回 'he'
* @Param: [str, separator]
* @return: java.lang.String
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/5/29 13:45
*/
public static String subStringBefore(String str,String separator){
if (!isNullString(str) && separator != null) {
if (separator.length() == 0) {
return "";
} else {
int pos = indexOfIgnoreCase(str,separator);
return pos == -1 ? str : str.substring(0,pos);
}
} else {
return str;
}
}
/*
* @Description: 截取特定字符後面的字符串(不區分大小寫),regionMatches方法可控制是否區分
* 傳 'hello' 'l' 返回 'lo'
* @Param: [str, separator]
* @return: java.lang.String
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/6/5 13:53
*/
public static String subStringAfter(String str,String separator) {
if (!isNullString(str)) {
if (isNullString(separator)){
return "";
} else {
int pos = indexOfIgnoreCase(str,separator);
return pos == -1 ? "" : str.substring(pos + separator.length());
}
} else {
return str;
}
}
/*
* @Description: 截取特定字符後面的字符串(不區分大小寫)
* @Param: [str, separator]
* @return: java.lang.String
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/6/5 18:54
*/
public static String subStringAfterLastIgnoreCase(String str, String separator) {
if (isNullString(str) || isNullString(separator)) {
return "";
} else {
String tempStr = str.toUpperCase();
String tempSeparator = separator.toUpperCase();
int index = tempStr.lastIndexOf(tempSeparator);
if (index == -1) {
return str;
} else {
String result = str.substring(index + separator.length());
return result;
}
}
}
/*
* @Description: 截取特定字符前面的字符串(不區分大小寫)
* @Param: [str, separator]
* @return: java.lang.String
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/6/5 19:30
*/
public static String subStringBeforeLastIgnoreCase(String str,String separator) {
if (isNullString(str) || isNullString(separator)) {
return "";
} else {
String tempStr = str.toUpperCase();
String tempSeparator = separator.toUpperCase();
int index = tempStr.lastIndexOf(tempSeparator);
if (index == -1) {
return str;
} else {
String result = str.substring(0,index);
return result;
}
}
}
/*
* @Description:
* @Param: [str, searchStr]
* @return: int
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/5/29 14:28
*/
public static int indexOfIgnoreCase(String str, String searchStr) {
return indexOfIgnoreCase(str, searchStr, 0);
}
/*
* @Description:
* @Param: [str, searchStr, startPos]
* @return: int
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/6/5 13:47
*/
public static int indexOfIgnoreCase(String str, String searchStr, int startPos) {
int spos = startPos;
if (str != null && searchStr != null) {
if (startPos < 0) {
spos = 0;
}
int endLimit = str.length() - searchStr.length() + 1;
if(spos > endLimit) {
return -1;
} else if (searchStr.length() == 0){
return spos;
} else {
for (int i = spos; i < endLimit; i++){
if(str.regionMatches(true, i, searchStr, 0,searchStr.length())) {
return i;
}
}
return -1;
}
} else {
return -1;
}
}
/*
* @Description: 給字符串前後拼一個單引號,便於sql字符拼接
* @Param: [str]
* @return: java.lang.String
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/6/5 14:02
*/
public static String singleQuotoAndEscape (String str) {
if (!isNullString(str)) {
StringBuffer sb = new StringBuffer(str.length() + 3);
sb.append("'");
sb.append(str.replaceAll("'","''"));
sb.append("'");
return sb.toString();
} else {
return "''";
}
}
/*
* @Description: 用於拼接LIKE查詢,字符前後加一個%
* @Param: [likeStr]
* @return:
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/6/5 14:10
*/
public static String escapeSqlLike(String str) {
if (!isNullString(str)) {
StringBuffer sb = new StringBuffer(str.length() + 3);
sb.append("%");
sb.append(str.replaceAll("'","''"));
sb.append("%");
return sb.toString();
} else {
return "''";
}
}
/*
* @Description: 將數組的字符分割後加上單引號
* @Param: [strs]
* @return: java.lang.String[]
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/6/5 14:30
*/
public static String[] singleQuotoAndEscape(String[] strs) {
String[] result = new String[strs.length];
for (int i = 0; i < strs.length; i++) {
String str = strs[i];
result[i] = singleQuotoAndEscape(str);
}
return result;
}
/*
* @Description: 字符串根據分隔符轉換成List
* @Param: [str, separator]
* @return: java.util.List<java.lang.String>
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/6/5 15:03
*/
public static List<String> splitToList(String str,String separator) {
if (str == null) {
return null;
} else {
ArrayList<String> list = new ArrayList();
String realSeparator = separator;
if (!str.equals("")) {
if (!"\\n".startsWith(separator) && !"\\r".startsWith(separator) && !"\\t".startsWith(separator)) {
if (!separator.startsWith("+") && !separator.startsWith("*") && !separator.startsWith("?")
&& !separator.startsWith("\\")) {
Pattern p = Pattern.compile(String.valueOf(separator.charAt(0)));
Matcher m = p.matcher("~!@#$%^&.<>-|");
if (m.find()) {
realSeparator = separator.replaceAll(separator,"\\" + separator);
}
} else {
realSeparator = separator.replaceAll(separator,"\\" + separator);
}
} else {
realSeparator = separator.replaceAll(separator,"\\" + separator);
}
String[] array = str.split(realSeparator);
for (int i = 0; i < array.length; ++i) {
list.add(array[i]);
}
}
return list;
}
}
/*
* @Description: 按豎線分隔轉成List
* @Param: [str]
* @return: java.util.List<java.lang.String>
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/6/5 17:36
*/
public static List<String> splitToListByUpStraight(String str) {
List<String> list = new ArrayList();
if (str == null) {
return null;
} else if (str.equals("")) {
list.add("");
return list;
} else {
String[] array = str.split("\\|");
for (int i = 0; i < array.length; ++i) {
list.add(array[i]);
}
return list;
}
}
/*
* @Description: 在str把傳入的stringsToReplace替換爲空
* @Param: [str, stringsToReplace]
* @return: java.lang.String
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/6/5 17:42
*/
public static String replaceAllToEmpty(String str,String... stringsToReplace) {
if (str == null) {
return null;
} else if (stringsToReplace.length == 0) {
return str;
} else {
String replacedStr = str;
String[] strsToReplace = stringsToReplace;
int len = stringsToReplace.length;
for (int i = 0; i < len; i++) {
String toReplace = strsToReplace[i];
if (toReplace != null && !"".equals(toReplace)) {
if (!"\\n".startsWith(toReplace) && !"\\r".startsWith(toReplace) && !"\\t".startsWith(toReplace)) {
if (!toReplace.startsWith("+") && !toReplace.startsWith("*") && !toReplace.startsWith("?")
&& !toReplace.startsWith("\\")) {
Pattern p = Pattern.compile(String.valueOf(toReplace.charAt(0)));
Matcher m = p.matcher("~!@#$%^&.<>-|");
if (m.find()) {
toReplace = toReplace.replaceAll(toReplace,"\\" + toReplace);
}
} else {
toReplace = toReplace.replaceAll(toReplace,"\\" + toReplace);
}
} else {
toReplace = toReplace.replaceAll(toReplace,"\\" + toReplace);
}
replacedStr = replacedStr.replaceAll(toReplace, "");
}
}
return replacedStr;
}
}
/*
* @Description: 在str把傳入的stringsToReplace替換爲targetValue
* @Param: [str, targetValue, stringsToReplace]
* @return: java.lang.String
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/6/5 18:30
*/
public static String replaceAllTargetValue(String str, String targetValue, String... stringsToReplace) {
if (str == null) {
return null;
} else if (stringsToReplace.length == 0) {
return str;
} else {
String replacedStr = str;
String[] strsToReplace = stringsToReplace;
int len = stringsToReplace.length;
for (int i = 0; i < len; i++) {
String toReplace = strsToReplace[i];
if (toReplace != null && !"".equals(toReplace)) {
if (!"\\n".startsWith(toReplace) && !"\\r".startsWith(toReplace) && !"\\t".startsWith(toReplace)) {
if (!toReplace.startsWith("+") && !toReplace.startsWith("*") && !toReplace.startsWith("?")
&& !toReplace.startsWith("\\")) {
Pattern p = Pattern.compile(String.valueOf(toReplace.charAt(0)));
Matcher m = p.matcher("~!@#$%^&.<>-|");
if (m.find()) {
toReplace = toReplace.replaceAll(toReplace,"\\" + toReplace);
}
} else {
toReplace = toReplace.replaceAll(toReplace,"\\" + toReplace);
}
} else {
toReplace = toReplace.replaceAll(toReplace,"\\" + toReplace);
}
replacedStr = replacedStr.replaceAll(toReplace, targetValue);
}
}
return replacedStr;
}
}
/*
* @Description: 將集合轉爲用 seperator連接的String字符串
* @Param: [coll, seperator]
* @return: java.lang.String
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/6/5 19:39
*/
public static String combineToString(Collection<String> coll, String seperator) {
if (coll == null || isNullString(seperator)) {
return "";
} else {
StringBuilder result = new StringBuilder();
Iterator it = coll.iterator();
while (it.hasNext()) {
String str = (String) it.next();
if (str != null) {
result.append(str).append(seperator);
}
}
if (result.length() > seperator.length()) {
result.setLength(result.length() - seperator.length());
}
return result.toString();
}
}
/*
* @Description: sub 在str中出現的次數
* @Param: [str, sub]
* @return: int
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/6/5 19:59
*/
public static int countMatches(String str,String sub) {
if (!isNullString(str) && !isNullString(sub)) {
int count = 0;
for (int idx = 0; (idx = str.indexOf(sub,idx)) !=-1; idx += sub.length()) {
++count;
}
return count;
} else {
return 0;
}
}
}
下面是一個測試類:
package com.java_foundation.util;
import java.util.Arrays;
import java.util.List;
/**
* @program: java_foundation
* @description: test
* @author: xiongbangwen <Email>[email protected]</Email>
* @create: 2020-05-29 11:18
**/
public class Test {
/*
* @Description:
* @Param: [args]
* @return: void
* @Author: xiongbangwen <Email>[email protected]</Email>
* @Date: 2020/5/29 13:59
*/
public static void main(String[] args) {
String name = "xiongbangwen";
String result = StringUtil.subStringBefore(name,"bang");
System.out.println(result);
//輸出:xiong
String result1 = StringUtil.subStringBefore(name,"G");
System.out.println(result1);
//輸出:xion
String result2 = StringUtil.subStringAfter(name,"bang");
System.out.println(result2);
//輸出:wen
String result3 = StringUtil.subStringAfter(name,"G");
System.out.println(result3);
//輸出:bangwen
String result4 = StringUtil.singleQuotoAndEscape(name);
System.out.println(result4);
//輸出:'xiongbangwen'
String result5 = StringUtil.escapeSqlLike(name);
System.out.println(result5);
//輸出:%xiongbangwen%
String[] result6 = StringUtil.singleQuotoAndEscape(new String[]{"xiong", "bang", "wen"});
System.out.println(Arrays.toString(new String[]{"xiong", "bang", "wen"}));
//輸出:[xiong, bang, wen]
System.out.println(Arrays.toString(result6));
//輸出:['xiong', 'bang', 'wen']
List<String> result7 = StringUtil.splitToList("xiong,bang,wen",",");
System.out.println(result7.toString());
//輸出:[xiong, bang, wen]
List<String> result8 = StringUtil.splitToListByUpStraight("xiong | bang | wen");
System.out.println(result8.toString());
//輸出:[xiong, bang, wen]
String result9 = StringUtil.replaceAllToEmpty(name,new String[]{"xiong", "bang"});
System.out.println(result9.toString());
//輸出:wen
String result10 = StringUtil.replaceAllTargetValue(name,"jizhiwen",new String[]{"xiong", "bang"});
System.out.println(result10.toString());
//輸出:jizhiwenjizhiwenwen
String result11 = StringUtil.combineToString(result7,"!");
System.out.println(result11);
//輸出:xiong!bang!wen
String result12 = StringUtil.subStringBeforeLastIgnoreCase(name,"bang");
System.out.println(result12);
//輸出:xiong
String result13 = StringUtil.subStringAfterLastIgnoreCase(name,"bang");
System.out.println(result13);
//輸出:xwen
int result14 = StringUtil.countMatches(name,"g");
System.out.println(result14);
//輸出:2
}
}