概述
本文主要就一些Java中String常用的Util的用法
1.List<String> 打印出以“,”分割元素的字符串
用法: String.join("分割符","集合")
List<String> list = new ArrayList<String>();
String listAsString = String.join(",",list);
2. String是否为number
public static boolean isNum(String str) {
Pattern pattern = Pattern.compile("^-?[0-9]+");
if (pattern.matcher(str).matches()) {
// 数字
return true;
} else {
// 非数字
return false;
}
}
3. String 是否含有中文
public static boolean isContainChinese(String str) {
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(str);
if (m.find()) {
return true;
}
return false;
}
4. Unicode to String
public static String unicodeToString(String str) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(str);
char ch;
while (matcher.find()) {
// group 6728
String group = matcher.group(2);
// ch:'木' 26408
ch = (char) Integer.parseInt(group, 16);
// group1 \u6728
String group1 = matcher.group(1);
str = str.replace(group1, ch + "");
}
return str;
}
5 String to Unicode
public static String gbEncoding(final String gbString) {
char[] utfBytes = gbString.toCharArray();
String unicodeBytes = "";
for (int i = 0; i < utfBytes.length; i++) {
String hexB = Integer.toHexString(utfBytes[i]);
if (hexB.length() <= 2) {
hexB = "00" + hexB;
}
unicodeBytes = unicodeBytes + "\\u" + hexB;
}
return unicodeBytes;
}