package io.cpic.commons.tools.utils;

import org.apache.commons.lang3.StringUtils; import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.*;

/**

  • 字符串操作

  • @author zpq */ public class StringUtil {

    private static final String HEX_STRING = "0123456789ABCDEF";

    private static final String BASE_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    /**

    • 替换字符串里内容,按Map Key 替换成value
    • @param map
    • @param context
    • @return String */ public static String morge(Map<String, String> map, String context) { for (String key : map.keySet()) { context = context.replaceAll("&" + key, map.get(key)); } return context; }

    /**

    • 功能描述:字符串str长度不足length长度前面补0
    • @param length 所需字符串长度
    • @param str 字符串实际长度
    • @return 指定位数的字符串长度 */ public static String getDecForLength(int length, String str) { StringBuilder temp = new StringBuilder(); for (int i = 0; i < length; i++) { temp.append("0"); } str = temp.toString() + str; return str.substring(str.length() - length); }

    /**

    • 字符串前增加指定位数的长度
    • @param len 长度位数
    • @param str 字符串
    • @return 长度+字符串 */ public static String getAddLengthString(int len, String str) { StringBuilder temp = new StringBuilder(); String strLen = str.getBytes().length + ""; for (int i = 0; i < len; i++) { temp.append("0"); } strLen = temp.toString() + strLen; return strLen.substring(strLen.length() - len) + str; }

    /**

    • 随机生成 指定位数位字符串
    • @return */ public static String generateCodeFromString(int codeCount) { try { int number; int length = BASE_STRING.length(); StringBuilder result = new StringBuilder(); Random random = new Random(); for (int i = 0; i < codeCount; i++) { number = random.nextInt(length); result.append(BASE_STRING.substring(number, number + 1)); } return result.toString(); } catch (Exception e) { e.printStackTrace(); return ""; } }

    /**

    • 将16进制的字符串,两位一压缩,转化为Byte数组
    • @param str 待转化的字符串
    • @return 压缩后字符串 */ public static byte[] hexStr2Byte(String str) { byte[] bs = new byte[str.length()]; byte[] bytes = new byte[str.length() / 2]; int[] ints = new int[str.length() / 2]; for (int i = 0; i < str.length(); i++) { if ((str.charAt(i) >= 'A') && (str.charAt(i) <= 'F')) { bs[i] = (byte) (str.charAt(i) - 'A' + 10); } else if ((str.charAt(i) >= 'a') && (str.charAt(i) <= 'f')) { bs[i] = (byte) (str.charAt(i) - 'a' + 10); } else { bs[i] = (byte) (str.charAt(i) - '0'); } } int bs2 = 2; for (int i = 0; i < bs.length / bs2; i++) { bytes[i] = (byte) ((bs[i * 2] << 4) ^ bs[i * 2 + 1]); ints[i] = (bs[i * 2] << 4) ^ bs[i * 2 + 1]; } return bytes; }

    /**

    • 二进制转换成十六进制字符串
    • @param b
    • @return */ public static String byte2hex(byte[] b) { StringBuffer sb = new StringBuffer(b.length); String sTemp; for (int i = 0; i < b.length; i++) { sTemp = Integer.toHexString(0xFF & b[i]); if (sTemp.length() < 2) { sb.append(0); } sb.append(sTemp.toUpperCase()); } return sb.toString().toUpperCase(); }

    /**

    • 二行制转字符串
    • @param b
    • @return String */ public static String int2hex(int[] b) { StringBuffer sb = new StringBuffer(b.length); String sTemp; for (int i = 0; i < b.length; i++) { sTemp = Integer.toHexString(0xFF & b[i]); if (sTemp.length() < 2) { sb.append(0); } sb.append(sTemp.toUpperCase()); } return sb.toString().toUpperCase(); }

    /**

    • 字符串转BCD码
    • @param str
    • @return */ public static byte[] str2bcd(String str) { int i2 = 2 ; if (str.length() % i2 != 0) { str = "0" + str; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); char[] cs = str.toCharArray(); for (int i = 0; i < cs.length; i += i2) { int high = cs[i] - 48; int low = cs[i + 1] - 48; baos.write(high << 4 | low); } return baos.toByteArray(); }

    /**

    • BCD码转String
    • @param bytes
    • @return */ public static String bcd2str(byte[] bytes) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { int h = ((bytes[i] & 0xff) >> 4) + 48; sb.append((char) h); int l = (bytes[i] & 0x0f) + 48; sb.append((char) l); } return sb.toString(); }

    /**

    • 将字符串编码成16进制数字,适用于所有字符(包括中文)
    • @param str
    • @return */ public static String str2hex(String str) { // 根据默认编码获取字节数组 byte[] bytes = str.getBytes(); StringBuilder sb = new StringBuilder(bytes.length * 2); // 将字节数组中每个字节拆解成2位16进制整数 for (int i = 0; i < bytes.length; i++) { sb.append(HEX_STRING.charAt((bytes[i] & 0xf0) >> 4)); sb.append(HEX_STRING.charAt((bytes[i] & 0x0f) >> 0)); } return sb.toString(); }

    /**

    • 将16进制数字解码成字符串,适用于所有字符(包括中文)
    • @param bytes
    • @return String */ public static String hex2str(String bytes) { ByteArrayOutputStream baos = new ByteArrayOutputStream( bytes.length() / 2); // 将每2位16进制整数组装成一个字节 int i2 = 2; for (int i = 0; i < bytes.length(); i += i2) { baos.write((HEX_STRING.indexOf(bytes.charAt(i)) << 4 | HEX_STRING.indexOf(bytes.charAt(i + 1)))); } return new String(baos.toByteArray()); }

    public static String hexStr2Str(String hexStr) { String str = "0123456789ABCDEF"; char[] hexs = hexStr.toCharArray(); byte[] bytes = new byte[hexStr.length() / 2]; int n; for (int i = 0; i < bytes.length; i++) { n = str.indexOf(hexs[2 * i]) * 16; n += str.indexOf(hexs[2 * i + 1]); bytes[i] = (byte) (n & 0xff); } return new String(bytes); }

    /**

    • 返回文件路径; 如果末尾有/则不添加,如果没有则添加/
    • @param filepath 文件路径
    • @return String */ public static String getPath(String filepath) { int length = filepath.length() - 1; String splitString = "\"; if (filepath.indexOf(splitString) != -1) { if (filepath.lastIndexOf(splitString) < length) { return filepath = filepath + "/"; } } else { String splitString1 = "/"; if (filepath.lastIndexOf(splitString1) < length) { return filepath = filepath + "/"; } } return filepath; }

    /**

    • 查询map集合中的value纸是否为空
    • @param map
    • @return boolean */ public static boolean checkMapValueIsNull(Map<String, List<String>> map) { Set<Map.Entry<String, List<String>>> entryseSet = map.entrySet(); for (Map.Entry<String, List<String>> entry : entryseSet) { List<String> value = entry.getValue(); String tempBlank=""; if (value == null || value.size() == 0 || value.get(0).equals(tempBlank)) { return true; } } return false; }

    public static boolean checkMapIsNull(Map<String, String> map) { for (Map.Entry<String, String> entry : map.entrySet()) { String value = entry.getValue(); if ("null".equals(value) || value == null || "".equals(value)) { return true; } } return false; }

    public static int getCode() { int code = (int) (Math.random() * 9999 + 1000); int code9999 = 9999; if (code > code9999) { code = code - 1000; } return code; }

    public static String deleteWrap(String message, String str) { int index = message.lastIndexOf(str); System.out.println("index::::" + index); int len = str.length(); message = message.substring(0, index) + message.substring(index + len, message.length()); return message; }

    /**

    • 获取uuid
    • @return String
    • @date 2016-04-14 */ public static String getUuIdString() { return UUID.randomUUID().toString(); }

    /**

    • 获取实体含有数据的实体字段和字段值
    • @return String
    • @date 2016-04-14 */ public static String getUpdateData(Object o) { String data = ""; Field[] fields = o.getClass().getDeclaredFields(); for (Field field : fields) { Method method = null; Object value = null; String name = field.getName(); if (!"id".equalsIgnoreCase(name)&&!"SERIAL_VERSION_UID".equals(name)) { String upperName = name.substring(0, 1).toUpperCase() + name.substring(1); try { method = o.getClass().getMethod("get" + upperName); value = method.invoke(o); if (value != null && !"".equals(value + "")) { data += name + "='" + value + "',"; } } catch (Exception e) { e.printStackTrace(); } } } if (data.length() > 0) { data = data.substring(0, data.length() - 1); } return data; }

    /**

    • 字符串非空判断
    • @param str
    • @return boolean / public static boolean isNullOrEmpty(String str){ boolean flag=false; String stringNull = "null", stringQm = "''"; if(str==null||"".equals(str)||stringNull.equals(str) || stringQm.equals(str) || StringUtils.isBlank(str)){ flag=true; } return flag; } /*
    • 字符串转base64字符串
    • @param str
    • @return String */ public static String getBase64(String str) {
      byte[] b = null;
      String s = null;
      try {
      b = str.getBytes("utf-8");
      } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      }
      if (b != null) {
      s = new BASE64Encoder().encode(b);
      }
      return s;
      }

    /**

    • 取时间戳的后6位
    • @return */ public static String getTimeMillis(){ Long d = System.currentTimeMillis(); String s = d.toString(); return s.substring(s.length()-6,s.length()); }

    /**

    • bytes[] 转int
    • @param bytes
    • @return */ public static int byteArrayToInt(byte[] bytes) { int value=0; value = ((bytes[3] & 0xff)<<24)| ((bytes[2] & 0xff)<<16)| ((bytes[1] & 0xff)<<8)| (bytes[0] & 0xff); return value; }

    /**

    • 将指定byte数组以16进制的形式打印到控制台
    • @param hint
    •        String
      
    • @param b
    •        byte[]
      
    • @return void */ public static void printHexString(String hint, byte[] b) { System.out.print(hint); for (int i = 0; i < b.length; i++) { String hex = Integer.toHexString(b[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } System.out.print(hex.toUpperCase() + " "); } System.out.println(""); }

    /**

    • @param b
    •        byte[]
      
    • @return String */ public static String bytes2HexString(byte[] b) { String ret = ""; for (int i = 0; i < b.length; i++) { String hex = Integer.toHexString(b[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } ret += " 0x" + hex.toUpperCase(); } return ret; }

    /**

    • 将两个ASCII字符合成一个字节; 如:"EF"–> 0xEF
    • @param src0
    •        byte
      
    • @param src1
    •        byte
      
    • @return byte */ public static byte uniteBytes(byte src0, byte src1) { byte b0 = Byte.decode("0x" + new String(new byte[] {src0})).byteValue(); b0 = (byte) (b0 << 4); byte b1 = Byte.decode("0x" + new String(new byte[] { src1 })).byteValue(); byte ret = (byte) (b0 ^ b1); return ret; }

    /**

    • 将指定字符串src,以每两个字符分割转换为16进制形式 如:"2B44EFD9" –> byte[]{0x2B, 0×44, 0xEF,
    • 0xD9}
    • @param src
    •        String
      
    • @return byte[] */ public static byte[] hexString2Bytes(String src) { if (null == src || 0 == src.length()) { return null; } byte[] ret = new byte[src.length() / 2]; byte[] tmp = src.getBytes(); int i2 = 2; for (int i = 0; i < (tmp.length / i2); i++) { ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]); } return ret; }

    /**

    • <p>18位和非18位身份证处理均可成功处理</p>
    • <p>参数异常直接返回null</p>
    • @param str 任意字符串
    • @return 处理完成的字符串 / public static String idMask(String str) { int front = 0,end = 1; //不能为空 if (StringUtils.isBlank(str)) { return null; } // 如果长度小于 8 隐藏后四位 int len8 = 8, len11 = 11; if (str.length() <= len8){ front = 0; end = 4; }else if (str.length() == len11){ // 如果长度为11 隐藏前三 后四位 front = 3; end = 4; }else if (str.length() > len11){ // 如果长度大鱼11位 隐藏前六 后四位 front = 6; end = 4; } //需要截取的长度不能大于字符串本身长度 if ((front + end) > str.length()) { return str; } //需要截取的不能小于0 if (front < 0 || end < 0) { return str; } //计算的数量 int asteriskCount = str.length() - (front + end); StringBuffer asteriskStr = new StringBuffer(); for (int i = 0; i < asteriskCount; i++) { asteriskStr.append("*"); } String regex = "(\w{" + String.valueOf(front) + "})(\w+)(\w{" + String.valueOf(end) + "})"; return str.replaceAll(regex, "$1" + asteriskStr + "$3"); }

    /**

    • 姓名 加密
    • @param str 任意字符串
    • @return 处理完成的字符串 / public static String nameMask(String str) { int front = 1,end = 0; //不能为空 if (StringUtils.isBlank(str)) { return null; } // 如果长度2位 隐藏后1位 int len2 = 2, len3 = 3, len4 = 4; if (str.length() == len2){ front = 1; end = 0; }else if (str.length() == len3){ front = 1; end = 0; }else if (str.length() >= len4){ front = 2; end = 0; } //需要截取的长度不能大于字符串本身长度 if ((front + end) > str.length()) { return null; } //需要截取的不能小于0 if (front < 0 || end < 0) { return null; } //计算的数量 int asteriskCount = str.length() - (front + end); StringBuffer asteriskStr = new StringBuffer(); for (int i = 0; i < asteriskCount; i++) { asteriskStr.append("*"); } String regex = "([\w\d\D]{" + String.valueOf(front) + "})([\w\d\D]+)([\w\d\D]{" + String.valueOf(end) + "})"; return str.replaceAll(regex, "$1" + asteriskStr + "$3"); }

    public static void main(String[] args) { System.out.println(StringUtil.getDecForLength(2,"3")); }

    public static String bankAccountMask(String str) { int front = 0,end = 1; //不能为空 if (StringUtils.isBlank(str)) { return null; } // 如果长度小于 8 隐藏后四位 int len8 = 8, len11 = 11; if (str.length() <= len8){ front = 0; end = 4; }else if (str.length() == len11){ // 如果长度为11 隐藏前三 后四位 front = 3; end = 4; }else if (str.length() > len11){ // 如果长度大鱼11位 隐藏前六 后四位 front = 4; end = 4; } //需要截取的长度不能大于字符串本身长度 if ((front + end) > str.length()) { return null; } //需要截取的不能小于0 if (front < 0 || end < 0) { return null; } //计算的数量 int asteriskCount = str.length() - (front + end); StringBuffer asteriskStr = new StringBuffer(); for (int i = 0; i < asteriskCount; i++) { asteriskStr.append(""); } String regex = "(\w{" + String.valueOf(front) + "})(\w+)(\w{" + String.valueOf(end) + "})"; return str.replaceAll(regex, "$1" + asteriskStr + "$3"); } }