StringUtil 整理了工作中常用的字串操作:
replaceStr:遞歸實現子串替換。getFields:智慧分割(支援空白或 # 分隔符)。BQchange / QBchange:半角↔全角轉換(基於 Unicode 字節操作)。public static String replaceStr(String source, String beRep, String rep, String returnStr) {
if (source.indexOf(beRep) < 0) return source;
String head = source.substring(0, source.indexOf(beRep));
String body = rep + source.substring(source.indexOf(beRep) + beRep.length());
return replaceStr(head + body, beRep, rep, returnStr);
}
注意:遞歸深度受限於字串長度,大量替換建議用 StringBuilder 或 String.replaceAll。
public static String[] getFields(String test, String sep) {
sep = "\u0020"; // 預設空白
if (test.indexOf(sep) != -1 && test.indexOf(sep) > test.indexOf("#") && test.indexOf("#") != -1)
sep = "#";
else if (test.indexOf(sep) == -1)
sep = "#";
if (sep.equals("\u0020")) {
StringTokenizer st = new StringTokenizer(test.trim(), sep);
List list = new ArrayList<>();
while (st.hasMoreTokens()) list.add(st.nextToken());
return list.toArray(new String[0]);
} else {
return test.trim().split(sep);
}
}
public static final String BQchange(String qjStr) { // 半角→全角
StringBuilder sb = new StringBuilder();
for (int i = 0; i < qjStr.length(); i++) {
String ch = qjStr.substring(i, i+1);
byte[] b = ch.getBytes("Unicode");
if (b[3] != -1) { b[2] -= 32; b[3] = -1; }
sb.append(new String(b, "Unicode"));
}
return sb.toString();
}
原理:Unicode 編碼中,半角字元高位字節為 0,全角為 -1(0xFF),透過調整第 3 字節實現轉換。
public static void main(String[] args) {
String qj = "#?¥%……?*()";
String bj = "#@$%^&*()";
System.out.println("半角→全角:" + bj + " --> " + BQchange(bj));
System.out.println("全角→半角:" + qj + " --> " + QBchange(qj));
// 分割測試
String[] arr = getFields("23#99#99#99", "#");
for (String s : arr) System.out.println(s);
}
本文來自編程入門網:原文連結