Languages
[Edit]
EN

C# / .NET - random string (random text)

5 points
Created by:
Kate_C
19800

In C# / .NET it is possible to generate random text in few ways.

1. Random string example

public static class RandomUtils
{
	private static readonly string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
		"abcdefghijklmnopqrstuvwxyz" + 
		"0123456789";

	public static string generateText(int length)
	{
		Random random = new Random();
		StringBuilder builder = new StringBuilder(length);

		for (int i = 0; i < length; ++i)
		{
			int index = random.Next(ALPHABET.Length);

			builder.Append(ALPHABET[index]);
		}

		return builder.ToString();
	}
}

Example:

string value = RandomUtils.generateText(32);
Console.WriteLine(value);

Output:

inog93o8FXgBSy5kgali4RjF0JRUeMUf

2. Random characters example

public static class RandomUtils
{
	private static readonly string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
		"abcdefghijklmnopqrstuvwxyz" + 
		"0123456789";

	public static char[] generateChars(int length)
	{
		Random random = new Random();
		char[] result = new char[length];

		for (int i = 0; i < length; ++i)
		{
			int index = random.Next(ALPHABET.Length);

			result[i] = ALPHABET[index];
		}

		return result;
	}
}

Example:

char[] value = RandomUtils.generateChars(32);
Console.WriteLine(value);

Output:

atKK7quegNmtzHuKLK57kaVenhzsSCiA
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join