How to generate a random alpha-numeric string

前端 未结 30 2564
忘掉有多难
忘掉有多难 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

    1. Change String characters as per as your requirements.

    2. String is immutable. Here StringBuilder.append is more efficient than string concatenation.


    public static String getRandomString(int length) {
        final String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+";
        StringBuilder result = new StringBuilder();
    
        while(length > 0) {
            Random rand = new Random();
            result.append(characters.charAt(rand.nextInt(characters.length())));
            length--;
        }
        return result.toString();
    }
    

提交回复
热议问题