Java 隨機中文字符

        // Unicode中漢字所佔區域\u4e00-\u9fa5,將4e00和9fa5轉爲10進制
        int start = Integer.parseInt("4e00", 16);
        int end = Integer.parseInt("9fa5", 16);
        System.out.println(start);
        System.out.println(end);
        // 輸出結果
        // 19968
        // 40869

        // 隨機數
        Random random = new Random();
        int code = random.nextInt(end - start + 1) + start;

        // 轉爲字符
        String str = new String(new char[] { (char) code });
        System.out.println(str);

簡化代碼:

    public static String getRandomChinese() {
        return new String(new char[] { (char) (new Random().nextInt(20902) + 19968) });
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章