Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
3.33/5 (3 votes)
See more:
Hi i created one function for automatic random generation of string
The function i geiven below:



C#
public static string createRandomString(int Length)
       {
           string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
           Random randNum = new Random();
           char[] chars = new char[Length];
           int allowedCharCount = _allowedChars.Length;

           for (int i = 0; i < Length; i++)
           {
               chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
           }

           return new string(chars);
       }



here in length i am passing the varchar length..ie varchar(50) mean i am passing lenght 50.it randomly generate string takes 50 whole length



it generate string upto 50 characters

but i want variable lenght characters.that is if i gave length 50 it want to produce string like different length within 50 ..not exceeds 50

that is
eg;

addncvu
axccdfgghh
wdedglikdfdf
adsd
asdfeddfgdfgdfsggggfgfd
advefcvv
adfsadfafccffgbbb


like this i want to vary the length of string..how to generate it..how to mdodify the function i have written already..
anybody know tell me.........
Posted
Comments
RakeshMeena 23-Jun-11 2:06am    
I don't understand why somebody downvoted the question. My 5!

To randomize the length of the string, you create a random number from 1 to 50. And to do that, you use Random[^] class. Please see example below.

System.Random RandNum = new System.Random();
int MyRandomNumber = RandNum.Next(1, 51);
 
Share this answer
 
This article will give you a better approach. Further to generate random length string, the "length" i/p parameter should be provided by a "Random" class instance with max value as say 50.

Hope this helps!
 
Share this answer
 
You can use like this
This will generate a string which has a random length less than you have given in Length variable.

C#
public static string createRandomString(int Length)
       {
           string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
           Random randNum = new Random();
           char[] chars = new char[Length];
           int allowedCharCount = _allowedChars.Length;
           for (int i = 0; i < randNum.NextDouble(1,Length); i++)
           {
               chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
           }
           return new string(chars);
       }



You can Also Use this code to generate Random String
C#
String RndString;
Int Zero, Nine, A, Z, Count, RandNum;
Random randNum;
Random oRandom = New Random(System.DateTime.Now.Millisecond);
Zero = Asc("0");
Z = Asc("Z");
While (Count < randNum.NextDouble(1,Length))
{
    RandNum = oRandom.Next(Zero, Z);
    RndString = (char)RandNum;
    Count++;
}

Thanks.
 
Share this answer
 
v3
Comments
Peter_in_2780 23-Jun-11 1:54am    
This almost certainly won't do what you want. See my reply.
suryaswathi 23-Jun-11 1:54am    
Hi
i got error in for loop

for (int i = 0; i < randNum.NextDouble(1,Length); i++)

here i got no overload for method NextDounle takes 2 arguments
local variable Random randNum
please say how to rectify
Tarun Mangukiya almost got it. Calculating the output length in the loop test will change the target length every iteration of the loop, which is probably NOT what you want.

C#
public static string createRandomString(int Length)
       {
           string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
           Random randNum = new Random();
           int outputLength = randNum.NextDouble(1,Length);  //<<<<<<<<< moved out of loop
           char[] chars = new char[outputLength];  //<<<<<<<< use outputLength here
// not used           int allowedCharCount = _allowedChars.Length;
           for (int i = 0; i < outputLength ; i++)
           {
               chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
           }
           return new string(chars);
       }

Peter

[edit] used outputLength for chars[] size [/edit]
 
Share this answer
 
v2
Comments
suryaswathi 23-Jun-11 2:21am    
I want every time the string want to be generate is different length..
in that i got an error

int outputLength = randNum.NextDouble(1,Length); radnum .NextDouble not takes two arguments nu

wat i want to do
Peter_in_2780 23-Jun-11 2:29am    
int outputLength = (int)(randNum.NextDouble() * Length);
suryaswathi 23-Jun-11 2:55am    
sir thanks lkot.i got different variable lenth string

but again one pblm..in that in a row three field mean the three column in a row i getting same string..the string is unique

how to do..plz reply
Tarun Mangukiya 23-Jun-11 3:07am    
See My Edited Answer
Peter_in_2780 23-Jun-11 3:19am    
Your second code segment has exactly the same problem. Every time round the character loop, you are changing the loop upper limit. As well as that, the original question wanted characters from [A-za-z], not numerics and certainly not from [:;<=>?@] which yours will generate.
Hi,

If the requirement is just a random generated unique string, probably you might think of using the below.


C#
public static string createRandomString(int Length)
        {

            char[] charsToIgnore = {'0', '1','2', '3', '4', '5', '6', '7', '8', '9', '-'};
            string uniqueString = Guid.NewGuid().ToString();
            for(int i=0; i<charsToIgnore.Length; i++)
            {
                uniqueString = uniqueString.Replace(charsToIgnore[i].ToString(), "");
            }

            return uniqueString.Substring(0, Length);
        }



The Guid class always generates unique but in hex dec. But, you may trim the unwanted chars as done above.
Cheers
- Balaji
 
Share this answer
 
Comments
suryaswathi 23-Jun-11 2:41am    
hi i got this error

Index and length must refer to a location within the string.
Parameter name: length

how to rectify
thanks
i-balaji-mani 23-Jun-11 3:43am    
Can u show the exact error message and the line number?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900