ขั้นแรก ตั้งค่าสตริง
StringBuilder str = new StringBuilder();
ใช้การสุ่ม
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);
} ในทุกๆ การทำซ้ำข้างต้น จะมีการสร้างอักขระแบบสุ่มและผนวกเข้ากับรูปแบบสตริง
ต่อไปนี้เป็นตัวอย่างที่สมบูรณ์ −
ตัวอย่าง
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());
}
} ผลลัพธ์
ATTS