Generate a random character in C#
This post will discuss how to generate a random character in C#.
The Random.Next() method generates a pseudo-random value between the specified range. You can use it to generate a random character from a specified string. The idea is to generate a random number between 0 and the string’s length, and return the character at the generated random index from the string. In C#, this translates to:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; public class Example { public static char GetRandomChar(string s) { Random rand = new Random(); int index = rand.Next(s.Length); return s[index]; } public static void Main() { char ch = GetRandomChar("Hello"); Console.WriteLine(ch); } } |
Alternatively, if you need to generate a random character from the specified subset of characters, you can do like below. The solution the random character from range consisting of ASCII alphabets.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; public class Example { private static string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static char GetRandomAlphabet() { Random rand = new Random(); int index = rand.Next(0, chars.Length); return chars[index]; } public static void Main() { char ch = GetRandomAlphabet(); Console.WriteLine(ch); } } |
That’s all about generating a random character in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)