开发者

generating string from exited characters

I have a character array as shown below :

char[] pwdCharArray = "abcdefghijklmnopqrstuvwxyzABCDEFG" +
            "HIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+[]{}\\|;:'\",<" + 
        开发者_Python百科    ".>/?".ToCharArray();

and from this char array, i want to generate a string of minimum length 7 and all the characters in the string should be from the above char array. How to do this operation?


What's the maximum length? (You may want to parameterize the methods below to specify a minimum and maximum length.) Here's a simple way of doing it for exactly 7 characters:

Here's the C# version:

public string GeneratePassword(Random rng)
{
    char[] chars = new char[7];
    for (int i = 0; i < chars.Length; i++)
    {
        chars[i] = pwdCharArray[rng.Next(pwdCharArray.Length)];
    }
    return new string(chars);
}

Note that the Random instance should be passed in to avoid the common problem of creating many instances of Random. I have an article describing this problem and ways around it. In essence, you should use one instance of Random per thread - don't create a new instance every time you want to use one, and don't reuse the same instance across multiple threads.

In fact, for a genuine password which is guarding sensitive information, you probably shouldn't be using Random at all, but rather something like RNGCryptoServiceProvider (or less directly, the results of RandomNumberGenerator.Create()). This can be somewhat harder to use, but will give you much more secure random numbers.

In Java it would be pretty similar, but then I'd use SecureRandom (which is fortunately rather easier to use than its .NET counterpart). In this case, you can create a new instance each time:

public String generatePassword() {
    char[] chars = new char[7];
    SecureRandom rng = new SecureRandom();
    for (int i = 0; i < chars.length; i++) {
        chars[i] = pwdCharArray[nextInt(pwdCharArray.length)];
    }
    return new String(chars);
}


Generate 7 random numbers between 0 and yourArray.length -1. Pick the corresponding char in the array and put it in your final String.

Here is the code with a StringBuilder:

StringBuilder sb = new StringBuilder();
Random random = new Randdom();
for(int i=0; i<7; i++) {
    sb.append(pwdCharArray[random.nextInt(0, pwdCharArray.length -1)]);
}
return sb.toString();


(C# example)

Random rand = new Random();
char[] arr = new char[rand.Next(7,15)];
for(int i = 0 ; i < arr.Length ; i++) {
    arr[i] = pwdCharArray[rand.Next(pwdCharArray.Length)];
}
string pwd = new string(arr);


Here is a solution in Java, with variable length of the word, and test of working:

import java.util.*;

public class RandomWord {

    // Valid characters
    private static String VALID_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFG" +
            "HIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+[]{}\\|;:'\",<.>/?";

    // Minimal length thw word can have
    private static int MIN_LENGTH = 7;
    // Maximal length will be MIN_LENGTH + THRESHOLD - 1
    private static int THRESHOLD = 10;

    // Generate a random number generator.
    // The time in millis is used as seed prevents the numbers to be always the same in same order
    Random randomGenerator =  new Random(System.currentTimeMillis());

    public String generateWord () {
        // Actual length of the word (from MIN_LENGTH to MIN_LENGTH + THRESHOLD - 1)
        int length = MIN_LENGTH + randomGenerator.nextInt(THRESHOLD);
        // Loop for every character
        StringBuilder word = new StringBuilder();
        for (int i = 0; i < length; i++) {
            // Appends one more random char
            word.append(VALID_CHARACTERS.charAt(randomGenerator.nextInt(VALID_CHARACTERS.length())));
        }
        // Returns the random word
        return word.toString();
    }

    // Test the class
    public static void main (String[] args) {
        // Instantiates and tests the class
        RandomWord randomWord = new RandomWord();
        for (int i = 0; i < 30; i++) {
            String word = randomWord.generateWord();
            System.out.println(word + " (" + word.length() + ")");
        }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜