Page 1 of 1

Random Characters or Strings

#1 blank_program  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 11
  • View blog
  • Posts: 280
  • Joined: 22-July 09

Posted 16 April 2011 - 09:37 AM

This is a tutorial going to be about generating a random character, string of characters, string of numbers, or a combination of the two strings.

I am going to use a console project with a second class called RandomString. I used very simple and generic names for my variables for the purpose of this tutorial but feel free to change them to suit your needs.

Previously I wrote the same tutorial using the ASCII values for all the characters but have since found a much better way to handle this that seems to be more extendable.

First lets get our console project started and create our RandomString class.
using System;
using System.Text;

namespace RandomStringTutorial
{
    class Program
    {
        static void Main()
        {
        }
    }

    class RandomString
    {
    }
}



Next we need to declare our available characters. I am going to setup two of them, one of capital and lower case letters,and then another of numbers just so we can use both easily. These strings are going to go in the RandomString class. You may notice the position of the zero in the numbers is at the front, I did this just to keep them in order from lowest to highest though its actual position doesn't matter.

    class RandomString
    {
        private string AvailableCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        private string AvailableNumbers = "0123456789";
    }



Something to note about these two strings is that the order really has no particular order the characters need to be in. You can also create another one for symbols if you want or even merge the numbers if that is important to you. I keep them separate for this case though due to the end result I aim to achieve.

Then declare a new instance of thr Random class.

    class RandomString
    {
        private string AvailableCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        private string AvailableNumbers = "0123456789";

        private Random rand = new Random();
    }



Next we can create our methods.
You will notice the two private methods, these are going to be used to do most of the generation of the strings and then we have our private methods to choose the type.
        private char SelectChar(string CharacterList)
        {
        }

        private string GenerateString(string CharacterList)
        {
        }

        public char NextChar()
        {
        }

        public string NextString(int Length, bool IncludeNumbers = false)
        {
        }

        public string NextNumericString(int Length)
        {
        }



Now let's develop each method individually.
First we will start with the two private methods.

Since it's just a single character we can just return that without much of a problem. However we should note that strings do allow for an index parameter which will we use for the single character by passing it the random number, we will have the number be between 0 and whatever the length of the character list is to avoid index errors.

This method will return just the single character which is what we want for our purposes. There is not much to this beyond the string index which might not be completely obvious right away.
        private char GenerateChar(string CharacterList)
        {
            return CharacterList[rand.Next(0, CharacterList.Length)];
        }



Next we will develop the entire string made up of the random characters.

We are going to use the StringBuilder to put the string together and have it made up of more random characters. Right now I use the same code as the GenerateChar method to determine what willbe appended, however we could just as easily call that method if we wanted. When done we just return whatever makes up the StringBuilder array as a string.
        private string GenerateString(int Length, string CharacterList)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < Length; i++)
            {
                sb.Append(GenerateChar(CharacterList));
            }

            return sb.ToString();
        }



Now for the public methods I am just going to lump them all together since they just call one of the two previous methods.

One thing to note is the NextString method I included an optional parameter. If the user wants it to be a combination of both they can provide the value, but if not then it can be left out and will still return a random string with no adverse effect. Otherwise nothing much to note here since we just called the methods we wrote previously.
        public char NextChar()
        {
            return SelectChar(AvailableCharacters);
        }

        public string NextString(int Length, bool IncludeNumbers = false)
        {
            if (IncludeNumbers)
            {
                return GenerateString(Length, AvailableCharacters + AvailableNumbers);
            }
            else
            {
                return GenerateString(Length, AvailableCharacters);
            }
        }

        public string NextNumericString(int Length)
        {
            return GenerateString(Length, AvailableNumbers);
        }



So now let's view the entire class completed and then we will implement it in our console to test the output. One thing to note is the lack of an access keyword on the class, this is because we did this all in one project. If you want to make it a separate class be sure to include one.
    class RandomString
    {
        private string AvailableCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        private string AvailableNumbers = "0123456789";

        private Random rand = new Random();

        private char SelectChar(string CharacterList)
        {
            return CharacterList[rand.Next(0, CharacterList.Length)];
        }

        private string GenerateString(int Length, string CharacterList)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < Length; i++)
            {
                sb.Append(SelectChar(CharacterList));
            }

            return sb.ToString();
        }

        public char NextChar()
        {
            return SelectChar(AvailableCharacters);
        }

        public string NextString(int Length, bool IncludeNumbers = false)
        {
            if (IncludeNumbers)
            {
                return GenerateString(Length, AvailableCharacters + AvailableNumbers);
            }
            else
            {
                return GenerateString(Length, AvailableCharacters);
            }
        }

        public string NextNumericString(int Length)
        {
            return GenerateString(Length, AvailableNumbers);
        }
    }



Now for our console let's just add some looks and provide the proper parameters. You will notice I did not use the NextChar method directly, this is because the string methods we wrote actually do them. We can however make a loop ourself to test it if we really wanted to but I do not feel it is nessesary. I used large blocks for the output but you can test with any values you want.
            RandomString rs = new RandomString();

            Console.WriteLine("Characters only:");
            for (int i = 0; i < 16; i++)
            {
                Console.WriteLine(rs.NextString(48));
            }

            Console.WriteLine("Numbers only:");
            for (int i = 0; i < 16; i++)
            {
                Console.WriteLine(rs.NextNumericString(48));
            }

            Console.WriteLine("Combo:");
            for (int i = 0; i < 16; i++)
            {
                Console.WriteLine(rs.NextString(48, true));
            }

            Console.ReadLine();



And that's it, we now can generate random characters, numbers, or strings up to a specified length. There is a method to even mix both letters and numbers.

I will be updating this later to allow the user to choose if they wanta specified number of characters followed by numbers or vice versa. If anyone has any suggestions for mergingmy NextString methods feel free to post them or let me know.

Is This A Good Question/Topic? 0
  • +

Replies To: Random Characters or Strings

#2 Listen...  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 02-July 11

Posted 02 July 2011 - 03:59 AM

Sound Good!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1