如何在java中随机生成常用汉字

Python019

如何在java中随机生成常用汉字,第1张

/** * 原理是从汉字区位码找到汉字。在汉字区位码中分高位与底位, 且其中简体又有繁体。位数越前生成的汉字繁体的机率越大。 * 所以在本例中高位从171取,底位从161取, 去掉大部分的繁体和生僻字。但仍然会有!! * */@Testpublic void create() throws Exception { String str = null int hightPos, lowPos// 定义高低位 Random random = new Random() hightPos = (176 + Math.abs(random.nextInt(39)))//获取高位值 lowPos = (161 + Math.abs(random.nextInt(93)))//获取低位值 byte[] b = new byte[2] b[0] = (new Integer(hightPos).byteValue()) b[1] = (new Integer(lowPos).byteValue()) str = new String(b, "GBk")//转成中文 System.err.println(str) } /** * 旋转和缩放文字 * 必须要使用Graphics2d类 */public void trans(HttpServletRequest req, HttpServletResponse resp) throws Exception{ int width=88 int height=22 BufferedImage img = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB) Graphics g = img.getGraphics() Graphics2D g2d = (Graphics2D) g g2d.setFont(new Font("黑体",Font.BOLD,17)) Random r = new Random() for(int i=0i<4i++){ String str = ""+r.nextInt(10) AffineTransform aff = new AffineTransform() aff.rotate(Math.random(),i*18,height-5) aff.scale(0.6+Math.random(), 0.6+Math.random()) g2d.setTransform(aff) g2d.drawString(str,i*18,height-5) System.err.println(">:"+str) } g2d.dispose() ImageIO.write(img, "JPEG",resp.getOutputStream()) }

数字,字母比较简单。

//手写的,省略了一部分String szzm = "0123...789abc...xyzABC...XYZ"StringBuilder bu = new StringBuilder()for(int i = 0i<6i++){bu.append(szzm.charAt(new Random().nextInt(szzm.length())))}System.out.println(bu.toString())

汉字复杂一些。我的方法是数字区间,19968~40869 之间 int 转char 都会变成汉字。

不过这个范围有点大,2w多汉字,有繁体的,还有生僻字。 如果不怕麻烦,汉字也可和数字一样,弄个汉字表。

StringBuilder bu = new StringBuilder()int base = 19968;int qujian = 40869 - 19968for(int i = 0i<6i++){int rand = base + new Random().nextInt(qujian) bu.append((char)rand)}System.out.println(bu.toString())