How to generate a random alpha-numeric string

前端 未结 30 2456
忘掉有多难
忘掉有多难 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条回答
  •  野的像风
    2020-11-21 06:02

    Using Dollar should be as simple as:

    // "0123456789" + "ABCDE...Z"
    String validCharacters = $('0', '9').join() + $('A', 'Z').join();
    
    String randomString(int length) {
        return $(validCharacters).shuffle().slice(length).toString();
    }
    
    @Test
    public void buildFiveRandomStrings() {
        for (int i : $(5)) {
            System.out.println(randomString(12));
        }
    }
    

    It outputs something like this:

    DKL1SBH9UJWC
    JH7P0IT21EA5
    5DTI72EO6SFU
    HQUMJTEBNF7Y
    1HCR6SKYWGT7
    

提交回复
热议问题