自動生成名字工具類,copy即可用
阿新 • • 發佈:2018-12-12
public class CharUtil { /** * 將字串轉換成相應的字元編碼 * @param s * @return */ public static String bytes2HexString(String s) { byte[] b = s.getBytes(); s = ""; for (int i = 0; i < b.length; i++) { String hex = Integer.toHexString(b[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } s = s + hex.toUpperCase(); } return s; } /** * 隨機生成漢字 * @return */ public static String getRandomChar() { String str = ""; int highCode; int lowCode; Random random = new Random(); highCode = (176 + Math.abs(random.nextInt(39))); //B0 + 0~39(16~55) 一級漢字所佔區 lowCode = (161 + Math.abs(random.nextInt(93))); //A1 + 0~93 每區有94個漢字 byte[] b = new byte[2]; b[0] = (Integer.valueOf(highCode)).byteValue(); b[1] = (Integer.valueOf(lowCode)).byteValue(); try { str = new String(b, "GBK"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return str; } /** * 隨機生成2-4個字的名字 * @return */ public static String getRandomName() { Random random = new Random(); //名字的個數 int charNum = random.nextInt(4) % 3 + 2; String resultName = ""; for (int i= 0 ; i<charNum; i++) { String nameWord = getRandomChar(); resultName += nameWord; } return resultName; }
直接調方法中getRandomName()方法就行。