字串工具類
阿新 • • 發佈:2020-07-27
public class StringUtils extends org.apache.commons.lang3.StringUtils {
private static final char SEPARATOR = '_';
private static final String CHARSET_NAME = "UTF-8";
/**
* 轉換為位元組陣列
* @param str
* @return
*/
public static byte[] getBytes(String str){
if (str != null){
try {
return str.getBytes(CHARSET_NAME);
} catch (UnsupportedEncodingException e) {
return null;
}
}else{
return null;
}
}
/**
* 轉換為Boolean型別
* 'true', 'on', 'y', 't', 'yes' or '1' (case insensitive) will return true. Otherwise, false is returned.
*/
public static Boolean toBoolean(final Object val){
if (val == null){
return false;
}
return BooleanUtils.toBoolean(val.toString()) || "1".equals(val.toString());
}
/**
* 轉換為位元組陣列
* @param str
* @return
*/
public static String toString(byte[] bytes){
try {
return new String(bytes, CHARSET_NAME);
} catch (UnsupportedEncodingException e) {
return EMPTY;
}
}
public static String toString(Object obj) {
StringBuffer buffer = new StringBuffer();
if (obj != null) {
buffer.append(obj);
}
return buffer.toString();
}
/**
* 如果物件為空,則使用defaultVal值
* see: ObjectUtils.toString(obj, defaultVal)
* @param obj
* @param defaultVal
* @return
*/
public static String toString(final Object obj, final String defaultVal) {
return obj == null ? defaultVal : obj.toString();
}
/**
* 是否包含字串
* @param str 驗證字串
* @param strs 字串組
* @return 包含返回true
*/
public static boolean inString(String str, String... strs){
if (str != null){
for (String s : strs){
if (str.equals(trim(s))){
return true;
}
}
}
return false;
}
/**
* 替換掉HTML標籤方法
*/
public static String replaceHtml(String html) {
if (isBlank(html)){
return "";
}
String regEx = "<.+?>";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(html);
String s = m.replaceAll("");
return s;
}
/**
* 替換為手機識別的HTML,去掉樣式及屬性,保留回車。
* @param html
* @return
*/
public static String replaceMobileHtml(String html){
if (html == null){
return "";
}
return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>");
}
/**
* 替換為手機識別的HTML,去掉樣式及屬性,保留回車。
* @param txt
* @return
*/
public static String toHtml(String txt){
if (txt == null){
return "";
}
return replace(replace(Encodes.escapeHtml(txt), "\n", "<br/>"), "\t", " ");
}
/**
* 縮略字串(不區分中英文字元)
* @param str 目標字串
* @param length 擷取長度
* @return
*/
public static String