import java.io.UnsupportedEncodingException;
import java.util.Random;
/**
* @Description
* 参考 https://blog.csdn.net/glizhewen/article/details/124869501
*/
public class ChineseCharactersUtils {
public static void main(String[] args) {
ChineseCharactersUtils t = new ChineseCharactersUtils();
t.test();
t.test2();
String randomChar = t.randomChar(500);
System.out.println(randomChar);
}
public void test(){
String str = "";
int highPos;
int lowPos;
Random random = new Random();
highPos = (176 + Math.abs(random.nextInt(39)));
lowPos = (161 + Math.abs(random.nextInt(93)));
byte[] b = new byte[2];
b[0] = (Integer.valueOf(highPos)).byteValue();
b[1] = (Integer.valueOf(lowPos)).byteValue();
try {
str = new String(b, "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
char result = str.charAt(0);
System.out.println("result : " + result);
}
public void test2(){
char result = (char) (0x4e00 + (int) (Math.random() * (0x9fa5 - 0x4e00 + 1)));
System.out.println("result : " + result);
}
public String randomCharAt(Integer len){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
char result = (char) (0x4e00 + (int) (Math.random() * (0x9fa5 - 0x4e00 + 1)));
sb.append(result);
}
return sb.toString();
}
public String randomChar(Integer len){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
int highPos;
int lowPos;
Random random = new Random();
highPos = (176 + Math.abs(random.nextInt(39)));
lowPos = (161 + Math.abs(random.nextInt(93)));
byte[] b = new byte[2];
b[0] = (Integer.valueOf(highPos)).byteValue();
b[1] = (Integer.valueOf(lowPos)).byteValue();
try {
sb.append(new String(b, "GBK"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Java随机生成汉字
最新推荐文章于 2024-07-16 10:45:51 发布
2580

被折叠的 条评论
为什么被折叠?



