Languages
[Edit]
EN

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

5 points
Created by:
Barmar
338

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

C# / .NET - random

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join