There are situations where you need a random string which is built with specific characters. In this article you’ll see how to generate such string where both length and elements are totally up to you.
Algorithm is very simple. It uses for loop, so that in every iteration it extends an output string with randomly chosen character from previously defined collection.
Let’s start with specifying group of characters which are acceptable in our result. For the purpose of this example let’s use digits, lower-case letters and few special chars.
Next we need to instantiate two objects. One of StringBuilder class and one of Random class. First one will be used to build string with consecutive elements, and second will be used to generate random numbers.
Main part of this algorithm is a loop. By defining number of iterations, we specify length of output string (in our case it’s 10 chars length). First line of the loop’s body generates random index, which is used to retrieve character from previously defined collection. The number is picked from the range <0, chars.Length). Next line takes a single character from chars collection. And at the end chosen character is being appended to output object.
Now we can print randomly generated string.
Below full algorithm in more compressed form.
Warning
Above algorithm uses Random class which is a pseudo-number generator. You can read more about it here. As a result of what above method shouldn’t be used to generate strings which are expected to be secure (e.g. passwords). The way how to generate secure password is presented here.
Need Help with Your C# Projects?
We offer expert support and development services for projects of any size. Contact us for a free consultation and see how we can help you succeed.
CONTACT US NOW