开发者

add random characters to end of string?

String key = "test";

I have a key. It is 4 characte开发者_JS百科rs long. What i want to do is have a function which looks at the length of key and then adds random characters at the end to make it the length of 20?

So if ket was just 'te' it would add 18 random characters at the end. If key is 'test' it adds 16 random characters at the end.

??


Consider solution as follows. In here you will get both lowercase and upper case letters mixed in.

Example:

for (int i = 0; i < 5; i++) {
    System.out.println(getRandomString("test"));
}

will return:

testRBMuWIiibcyAAaGc
testOjvmVMoQPYGJKKUs
testBnCPLyqbTUFzQrOs
testgaFkzFtnsYHNkDJR
testsisbGHzItczsJYNK
public static String getRandomString(String s) {

    int i = 0;
    int randomNumber;

    boolean isUpperCase;

    StringBuilder response = new StringBuilder();
    Random randomNumberGenerator = new Random();

    while (i++ < MAX_LENGTH - s.length()) {
        isUpperCase = randomNumberGenerator.nextBoolean();
        randomNumber = randomNumberGenerator.nextInt(26) + 65;

        response.append(isUpperCase ? (char) randomNumber : 
                      Character.toLowerCase((char) randomNumber));
    }

    return response.insert(0, s).toString();
}


SO isn't about making others write your code... but to give you a starting point, take a look at this question, and modify to suit.


A terse solution is:

Random random = new Random();
String randomString = "test";
       for(;randomString.length() < 20 ;) {
            char randomChar = (char) random.nextInt(123);
            randomString += (Character.isLetterOrDigit(randomChar)) ? randomChar : ""; 
        }


if(password.length() != 20){
                while (password.length() != 20){
                    password += (char)String.valueOf(myRandom.nextInt()).charAt(0); 
                }
            }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜