宇筱博客

  • 解决办法
  • 学无止境
  • 记录时光
  • 百宝箱
宇筱博客
点滴记忆,汇聚成海。
  1. 首页
  2. 学无止境
  3. 正文

Java实现获取指定长度随机字符串

2021年1月4日 472点热度 0人点赞 0条评论

思路:使用assic码表,三个范围:数字(48-57),大写字母(65-90),小写字母(97-122)

  代码:

import java.util.Random; /** * 随机字符串工具 * * @author volitation <> * */
public class RandomString {
    /** * 获取指定长度随机字符串 * * @param length * @return */ public static String getRandomString(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(3);
            long result = 0;
            switch (number) {
            case 0:
                result = Math.round(Math.random() * 25 + 65);
                sb.append(String.valueOf((char) result));
                break;
            case 1:
                result = Math.round(Math.random() * 25 + 97);
                sb.append(String.valueOf((char) result));
                break;
            case 2:
                sb.append(String.valueOf(new Random().nextInt(10)));
                break;
            }
        }
        return sb.toString();
    } /**  * 测试验证  *  * @param args  */ public static void main(String[] args) {
        System.out.println(RandomString.getRandomString(5));
        System.out.println(RandomString.getRandomString(10));
        System.out.println(RandomString.getRandomString(15));
    }
}


//测试:
//NVadc
//8C1UH1Y0hS
//dfiXZMR22pv422I

ASCII码表:

 

原文连接:https://www.cnblogs.com/xiejn/p/14592050.html

标签: 暂无
最后更新:2021年1月4日

小渔民

这个人很懒,什么都没留下

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2025 宇筱博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

豫ICP备15017825号-2