Tuesday, June 29, 2010

Generate random string

Current code is generate string in defined length and include chars, numbers and symbols.

public static string GetRandomString(int size)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
int[] symbol = new[] { 33, 36, 38, 64, 94 };
int[] digits = new[] { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 };
int symbolsAmount = size / 3;
int digitAmount = size / 3;
for(int i = 0; i < size; i++)
{

int switcher = random.Next(3);
char ch;
if(switcher == 0 && symbolsAmount > 0)
{
int id = random.Next(symbol.Length);
ch = Convert.ToChar(symbol[id]);
symbolsAmount--;
}
else if(switcher == 1 && digitAmount > 0)
{
int id = random.Next(digits.Length);
ch = Convert.ToChar(digits[id]);
digitAmount--;
}
else
{
bool isLower = random.Next(2) == 0 ? false : true;
ch = Convert.ToChar(
Convert.ToInt32(
Math.Floor(26 * random.NextDouble() + ((isLower) ? 65 : 97))
)
);

}
builder.Append(ch);
}

return builder.ToString();
}

Wednesday, June 23, 2010

Monday, June 21, 2010