Blog of a Filipino Developer about C#, VB.NET, ASP.NET, Java, PHP, SQL Server, MySql and Oracle RSS 2.0
 Wednesday, November 28, 2007

Somebody sent me an email today asking me about an article I wrote a few years ago detailing how to generate random strings and numbers in C# and VB.NET. He asked me if I could add function to the code that creates a random character set to be used as a base for the allowed characters in the random string. I went on and hammered the solution and this what I built for him. I don't have enough time to explain the whole thing but I hope the code comments I added would be good enough to understand what I did with the code.

[----------------- C# Version -----------------]

using System;
using System.Collections.Generic;
using System.Text;

namespace KeithRull.ConsoleCentral
{
   class RandomStrings
   {
      //our default string size
      private const int CONST_MaxStringLenght = 10;

      //our default character string set
      private const string CONST_AllowedCharacterLiterals 
         = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

      //our randomizer
      Random randomNumber = new Random();

      /// <summary>
      /// Generate a random string using the default options
      /// </summary>
      /// <returns>the random string</returns>
      public string GenerateRandomString()
      {
         return GenerateRandomString(CONST_MaxStringLenght);
      }

      /// <summary>
      /// Create a random string based on a specified lenght
      /// </summary>
      /// <param name="lenght">the lenght of the desired lenght of the random string</param>
      /// <returns>the randomized string</returns>
      public string GenerateRandomString(int lenght)
      {
         return GenerateRandomString(lenght, CreateRandomStringSet());
      }

      /// <summary>
      /// Creates a random string based on a specific lenght and character set
      /// </summary>
      /// <param name="lenght">the lenght of the desired lenght of the random string</param>
      /// <param name="charsToUse">character set to use</param>
      /// <param name="randomizeSourceSet">defines whether the source set should be scrambled</param>
      /// <returns>the random string</returns>
      public string GenerateRandomString(int lenght, string charsToUse, bool randomizeSourceSet)
      {
         string randomString = String.Empty;

         if (randomizeSourceSet) {
            //scramble and jumble it
            randomString = GenerateRandomString(lenght, CreateRandomStringSet(charsToUse));
         }
         else {
            //use the default charset
            randomString = GenerateRandomString(lenght, charsToUse);
         }

         return randomString;
      }

      /// <summary>
      /// Creates a random string based on a specific lenght and character set
      /// </summary>
      /// <param name="lenght">the lenght of the desired lenght of the random string</param>
      /// <param name="charsToUse">character set to use</param>
      /// <returns>the random string</returns>
      public string GenerateRandomString(int lenght, string charsToUse)
      {
         //Create a new StringBuilder that would hold the random string.
         StringBuilder randomString = new StringBuilder();

         //Create a variable to hold the generated charater.
         char appendedChar;

         //Create a loop that would iterate from 0 to the specified value of intLenghtOfString
         for (int i = 0; i <= lenght; ++i)
         {
            int characterIndex = Convert.ToInt32(randomNumber.Next(i, charsToUse.Length - i));
            //Generate the char and assign it to appendedChar
            appendedChar = charsToUse[characterIndex];
            //Append appendedChar to randomString
            randomString.Append(appendedChar);
         }
         //Convert randomString to String and return the result.
         return randomString.ToString();
      }

      /// <summary>
      /// Returns a random set of characters based on the default literal set
      /// </summary>
      /// <returns>the random string</returns>
      private string CreateRandomStringSet()
      {
         //just use the default character set
         return CreateRandomStringSet(CONST_AllowedCharacterLiterals);
      }

      /// <summary>
      /// A function that returns a new set of characters based on an input set
      /// </summary>
      /// <param name="allowedCharacters">the source set</param>
      /// <returns>the new collection of characters</returns>
      private string CreateRandomStringSet(string allowedCharacters)
      {
         string randomizedString = String.Empty;

         //get a random string set size
         int randomSetLenght = allowedCharacters.Length * randomNumber.Next(1, CONST_MaxStringLenght);

         //while lenght of the random set is not the same as the source string lenght
         while (randomizedString.Length != randomSetLenght)
         {
            //add a new character
            randomizedString += GetRandomCharFromString(allowedCharacters);
         }

         //return our random string
         return randomizedString;
      }

      /// <summary>
      /// Gets a character from the the input string
      /// </summary>
      /// <param name="allowedCharacters">source string</param>
      /// <returns>a random character</returns>
      private char GetRandomCharFromString(string allowedCharacters)
      {
         return allowedCharacters[randomNumber.Next(allowedCharacters.Length - 1)];
      }
   }
}

[----------------- C# Usage -----------------]

using System;
using System.Collections.Generic;
using System.Text;

namespace KeithRull.ConsoleCentral
{
   class Program
   {
      static void Main(string[] args)
      {
         RandomStrings r = new RandomStrings();

         Console.WriteLine(r.GenerateRandomString());
         Console.WriteLine(r.GenerateRandomString(10));
         Console.WriteLine(r.GenerateRandomString(10, "qwerttyuioplkjhgfdsazxcvbnm1234567890QWERTYUIOPLKJHGFDSAZXCVBNM"));
         Console.WriteLine(r.GenerateRandomString(10, "[]{}<>!@#$%^&*()qwerttyuioplkjhgfdsazxcvbnm1234567890", true));
         Console.WriteLine(r.GenerateRandomString(10, "qwerttyuioplkjhgfdsazxcvbnm1234567890QWERTYUIOPLKJHGFDSAZXCVBNM", false));

         Console.ReadLine();
      }
   }
}

[----------------- VB.NET Version -----------------]

Imports System
Imports System.Collections.Generic
Imports System.Text

Namespace KeithRull.ConsoleCentral 
   Class RandomStrings 
      Private Const CONST_MaxStringLenght As Integer = 10 
      Private Const CONST_AllowedCharacterLiterals As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" 

      Private randomNumber As New Random() 

      ''' <summary> 
      ''' Generate a random string using the default options 
      ''' </summary> 
      ''' <returns>the random string</returns> 
      Public Function GenerateRandomString() As String 
         Return GenerateRandomString(CONST_MaxStringLenght) 
      End Function 

      ''' <summary> 
      ''' Create a random string based on a specified lenght 
      ''' </summary> 
      ''' <param name="lenght">the lenght of the desired lenght of the random string</param> 
      ''' <returns>a random string</returns> 
      Public Function GenerateRandomString(ByVal lenght As Integer) As String 
         Return GenerateRandomString(lenght, CreateRandomStringSet()) 
      End Function 

      ''' <summary> 
      ''' Creates a random string based on a specific lenght and character set 
      ''' </summary> 
      ''' <param name="lenght">the lenght of the desired lenght of the random string</param> 
      ''' <param name="charsToUse">character set to use</param> 
      ''' <param name="randomizeSourceSet">defines whether the source set should be scrambled</param> 
      ''' <returns></returns> 
      Public Function GenerateRandomString(ByVal lenght As Integer, ByVal charsToUse As String, ByVal randomizeSourceSet As Boolean) As String 
         Dim randomString As String = [String].Empty 

         If randomizeSourceSet Then 
            'scramble and jumble it 
            randomString = GenerateRandomString(lenght, CreateRandomStringSet(charsToUse)) 
         Else 
            'use the default charset 
            randomString = GenerateRandomString(lenght, charsToUse) 
         End If 

         Return randomString 
      End Function 

      Public Function GenerateRandomString(ByVal lenght As Integer, ByVal charsToUse As String) As String 
         'Create a new StringBuilder that would hold the random string. 
         Dim randomString As New StringBuilder() 

         'Create a variable to hold the generated charater. 
         Dim appendedChar As Char 
         For i As Integer = 0 To lenght 

            'Create a loop that would iterate from 0 to the specified value of intLenghtOfString 
            Dim characterIndex As Integer = Convert.ToInt32(randomNumber.[Next](i, charsToUse.Length - i)) 
            'Generate the char and assign it to appendedChar 
            appendedChar = charsToUse(characterIndex) 
            'Append appendedChar to randomString 
            randomString.Append(appendedChar) 
         Next 
         'Convert randomString to String and return the result. 
         Return randomString.ToString() 
      End Function 

      ''' <summary> 
      ''' Returns a random set of characters based on the default literal set 
      ''' </summary> 
      ''' <returns></returns> 
      Private Function CreateRandomStringSet() As String 
         Return CreateRandomStringSet(CONST_AllowedCharacterLiterals) 
      End Function 

      ''' <summary> 
      ''' A function that returns a new set of characters based on an input set 
      ''' </summary> 
      ''' <param name="allowedCharacters">the source set</param> 
      ''' <returns>the new collection of characters</returns> 
      Private Function CreateRandomStringSet(ByVal allowedCharacters As String) As String 
         Dim randomizedString As String = [String].Empty 

         'get a random string set size 
         Dim randomSetLenght As Integer = allowedCharacters.Length * randomNumber.[Next](1, CONST_MaxStringLenght) 

         'while lenght of the random set is not the same as the source string lenght 
         While randomizedString.Length <> randomSetLenght 
            'add a new character 
            randomizedString += GetRandomCharFromString(allowedCharacters) 
         End While 

         'return our random string 
         Return randomizedString 
      End Function 

      ''' <summary> 
      ''' Gets a character from the the input string 
      ''' </summary> 
      ''' <param name="allowedCharacters">source string</param> 
      ''' <returns>a random character</returns> 
      Private Function GetRandomCharFromString(ByVal allowedCharacters As String) As Char 
         Return allowedCharacters(randomNumber.[Next](allowedCharacters.Length - 1)) 
      End Function 
   End Class
End Namespace

[----------------- VB.NET Usage -----------------]

Imports System
Imports System.Collections.Generic
Imports System.Text

Namespace KeithRull.ConsoleCentral 
   Class Program 
      Private Shared Sub Main(ByVal args As String()) 
      Dim r As RandomStrings = New RandomStrings() 

      Console.WriteLine(r.GenerateRandomString()) 
      Console.WriteLine(r.GenerateRandomString(10)) 
      Console.WriteLine(r.GenerateRandomString(10, "qwerttyuioplkjhgfdsazxcvbnm1234567890QWERTYUIOPLKJHGFDSAZXCVBNM")) 
      Console.WriteLine(r.GenerateRandomString(10, "[]{}<>!@#$%^&*()qwerttyuioplkjhgfdsazxcvbnm1234567890", True)) 
      Console.WriteLine(r.GenerateRandomString(10, "qwerttyuioplkjhgfdsazxcvbnm1234567890QWERTYUIOPLKJHGFDSAZXCVBNM", False)) 

      Console.ReadLine() 
      End Sub 
   End Class
End Namespace

[----------------- Screenshot -----------------]

And that's how you create random strings in C# and VB.NET. Interested in the source code? You can download them here. RandomStrings.cs (4.61 KB) | RandomStrings.vb (5 KB)

Wednesday, November 28, 2007 6:08:02 PM (GMT Standard Time, UTC+00:00)  #    Comments [1] -
.NET | Fun Stuff
Archive
<November 2007>
SunMonTueWedThuFriSat
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2008
Keith Rull
Sign In
Statistics
Total Posts: 246
This Year: 43
This Month: 4
This Week: 0
Comments: 111
Themes
Pick a theme:
Ads
All Content © 2008, Keith Rull
DasBlog theme 'Business' created by Christoph De Baene (delarou)