EN
C# / .NET - generate random string (random text)
5 points
In C# / .NET it is possible to generate random text in few ways.
xxxxxxxxxx
1
public static class RandomUtils
2
{
3
private static readonly string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
4
"abcdefghijklmnopqrstuvwxyz" +
5
"0123456789";
6
7
public static string generateText(int length)
8
{
9
Random random = new Random();
10
StringBuilder builder = new StringBuilder(length);
11
12
for (int i = 0; i < length; ++i)
13
{
14
int index = random.Next(ALPHABET.Length);
15
16
builder.Append(ALPHABET[index]);
17
}
18
19
return builder.ToString();
20
}
21
}
Example:
xxxxxxxxxx
1
string value = RandomUtils.generateText(32);
2
Console.WriteLine(value);
Output:
xxxxxxxxxx
1
inog93o8FXgBSy5kgali4RjF0JRUeMUf
xxxxxxxxxx
1
public static class RandomUtils
2
{
3
private static readonly string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
4
"abcdefghijklmnopqrstuvwxyz" +
5
"0123456789";
6
7
public static char[] generateChars(int length)
8
{
9
Random random = new Random();
10
char[] result = new char[length];
11
12
for (int i = 0; i < length; ++i)
13
{
14
int index = random.Next(ALPHABET.Length);
15
16
result[i] = ALPHABET[index];
17
}
18
19
return result;
20
}
21
}
Example:
xxxxxxxxxx
1
char[] value = RandomUtils.generateChars(32);
2
Console.WriteLine(value);
Output:
xxxxxxxxxx
1
atKK7quegNmtzHuKLK57kaVenhzsSCiA