C# Random String Generators

8 03 2008

Heres a little bit of code for making random strings. I’m sure someone will find it useful. I used to use it a lot in web development. Not sure how useful it would be for software development but use it if you’d like to :)


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

namespace Ruf
{
public static class StringGnerator
{
public static Char[] charArray = { ‘-’, ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘p’, ‘q’, ‘r’, ’s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’, ‘1′, ‘2′, ‘3′, ‘4′, ‘5′, ‘6′, ‘7′, ‘8′, ‘9′, ‘0′, ‘_’ };

public static string RandomStr()
{
String returns = “”;
Random r = new Random();
for (int i = 0; i < 11; i++)
{
returns += “” + charArray[(int)(r.NextDouble() + 1.0 * 38.0)];
}
return returns;
}

public static string RandomStr(int Length)
{
String returns = “”;
Random r = new Random();
for (int i = 0; i < Length; i++)
{
returns += “” + charArray[(int)(r.NextDouble() + 1.0 * 38.0)];
}
return returns;
}

public static string RandomStr(int Seed, int Length)
{
String returns = “”;
Random r = new Random(Seed);
for (int i = 0; i < Length; i++)
{
returns += “” + charArray[(int)(r.NextDouble() + 1.0 * 38.0)];
}
return returns;
}

}
}


Actions

Information

5 responses

17 03 2008
benoit

Hi
Thanks for this code,

But :

using System.Linq; : I haven’t Linq in VS C# 2008

And

In RandomStr you indexoutofrange error

Bye

17 03 2008
theanti9

you dont actually need the System.Linq; You can remove it. and just do 37.0 instead of 38.0 and that should fix it :]

24 06 2008
Belthasar

This may be a little late but wouldn’t this work better?
charArray[r.Next(charArray.Length)];

charArray[(int)(r.NextDouble() + 1.0 * 38.0)]; This always returns 38.

20 05 2009
Ciplearyorelp

Great website: Hope to definitely visit again=)

5 11 2009
leggBeast

Not that this would have life-changing performance changes, but since you use “returns += x” to generate the random string, it actually has to allocate new space for every single iteration. += is like a function that returns a newly allocated string, and deallocates the old one altogether. Generating a string of length 38 would need to allocated 38 different strings before returning the result.

If you use a StringBuilder instead, and initialize it with a capacity of ‘length’, then you can do all the appending without re-allocating new strings every single time. If you’re making a lot of long strings, this can save a lot of time.

Leave a comment