Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to generate a string randomly using C#?
Firstly, set a string.
StringBuilder str = new StringBuilder();
Use Random.
Random random = new Random((int)DateTime.Now.Ticks);
Now loop through a number which is the length of the random string you want.
for (int i = 0; i < 4; i++) {
c = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
str.Append(c);
}
On every iteration above, a random character is generated and appended to form a string.
The following is the complete example −
Example
using System.Text;
using System;
class Program {
static void Main() {
StringBuilder str = new StringBuilder();
char c;
Random random = new Random((int)DateTime.Now.Ticks);
for (int i = 0; i < 4; i++) {
c = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
str.Append(c);
}
Console.WriteLine(str.ToString());
}
}
Output
ATTS
Advertisements