How to generate a random alpha-numeric string

前端 未结 30 2507
忘掉有多难
忘掉有多难 2020-11-21 05:38

I\'ve been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifie

相关标签:
30条回答
  • Surprising, no one here has suggested it, but:

    import java.util.UUID
    
    UUID.randomUUID().toString();
    

    Easy.

    The benefit of this is UUIDs are nice, long, and guaranteed to be almost impossible to collide.

    Wikipedia has a good explanation of it:

    " ...only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%."

    The first four bits are the version type and two for the variant, so you get 122 bits of random. So if you want to, you can truncate from the end to reduce the size of the UUID. It's not recommended, but you still have loads of randomness, enough for your 500k records easy.

    0 讨论(0)
  • 2020-11-21 06:15

    In one line:

    Long.toHexString(Double.doubleToLongBits(Math.random()));
    

    Source: Java - generating a random string

    0 讨论(0)
  • 2020-11-21 06:15
    public static String generateSessionKey(int length){
        String alphabet =
            new String("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); // 9
    
        int n = alphabet.length(); // 10
    
        String result = new String();
        Random r = new Random(); // 11
    
        for (int i=0; i<length; i++) // 12
            result = result + alphabet.charAt(r.nextInt(n)); //13
    
        return result;
    }
    
    0 讨论(0)
  • 2020-11-21 06:16
    public static String getRandomString(int length) {
        char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST".toCharArray();
    
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            char c = chars[random.nextInt(chars.length)];
            sb.append(c);
        }
        String randomStr = sb.toString();
    
        return randomStr;
    }
    
    0 讨论(0)
  • 2020-11-21 06:17

    Here it is a Scala solution:

    (for (i <- 0 until rnd.nextInt(64)) yield { 
      ('0' + rnd.nextInt(64)).asInstanceOf[Char] 
    }) mkString("")
    
    0 讨论(0)
  • 2020-11-21 06:17
    public static String randomSeriesForThreeCharacter() {
        Random r = new Random();
        String value = "";
        char random_Char ;
        for(int i=0; i<10; i++)
        {
            random_Char = (char) (48 + r.nextInt(74));
            value = value + random_char;
        }
        return value;
    }
    
    0 讨论(0)
提交回复
热议问题