【案例】Java随机生成汉字以及随机生成字母
生成汉字
-
先把一个汉子转为一个16进制的字符串,看看可以输出什么东东
-
public static String bytes2HexString(String s) { byte[] b = s.getBytes(); s = ""; for (int j = 0; j < b.length; j++) { String hex = Integer.toHexString(b[j] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } s = s + hex.toUpperCase(); } return s; } public static void main(String[] args) { String str = "啊啊啊"; char[] cs = str.toCharArray(); for (int i = 0; i < cs.length; i++) { String s = cs[0] + ""; System.out.print(bytes2HexString(s)); System.out.print(" "); } }
-
输出结果:
B0A1B0A1B0A1
-
生成汉字
-
//随机生成常见汉字 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; }
随机生成字母
-
public void testRandom1() throws Exception { String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; char[] c = s.toCharArray(); Random random = new Random(); for( int i = 0; i < 8; i ++) { System.out.println(c[random.nextInt(c.length)]); } }