How to generate a random string, and specify the length you want, or better generate unique string on specification you want

前端 未结 11 2327
一生所求
一生所求 2020-12-24 06:24

There is a library to generate Random numbers, so why isn\'t there a library for generation of random strings?

In other words how to generate a random string, and sp

11条回答
  •  轮回少年
    2020-12-24 07:15

    public  static String getAlphaNumericString(int n) {
    
            String AlphaNumericString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + "abcdefghijklmnopqrstuvxyz";
    
            StringBuilder sb = new StringBuilder(n);
    
            for (int i = 0; i < n; i++) {
    
                // generate a random number between
                // 0 to AlphaNumericString variable length
                int index = (int) (AlphaNumericString.length() * Math.random());
    
                // add Character one by one in end of sb
                sb.append(AlphaNumericString.charAt(index));
            }
    
            return sb.toString();
        }
    

提交回复
热议问题