Random

  • Thread starter Thread starter Ariel Gimenez
  • Start date Start date
A

Ariel Gimenez

Hi i need to generate a random string , can anybody give me an example of
how to do it in c#

thanks!
 
Hi Ariel,

This sounds a little bit like some homework assignment :P but here goes.

This method will make a random string of a given length out of small and
capital letters using ascii A-Z, a-z,

private string GenerateString(int length)
{
Random rand = new Random();
string randomString = "";
for(int i = 0; i < length; i++)
{
int small = rand.Next(2);
int letter = rand.Next(26);
if(small == 0)
letter += 65;
else
letter += 97;
randomString += Convert.ToChar(letter);
}
return randomString;
}


Happy coding!
Morten Wennevik [C# MVP]
 
Hi,

You could use the random generator, and then use a StringBuilder to append
them , all you have to do is make sure you generate printables characters.

Cheers,
 
Ariel Gimenez said:
Hi i need to generate a random string , can anybody give me an example of
how to do it in c#

If your objective is to get something irregular and/or unique you could use

System.Guid.NewGuid.ToString()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top