ในส่วนนี้ เราจะมาดูวิธีการสร้างสตริงตัวอักษรและตัวเลขแบบสุ่มโดยใช้ C++ เราให้บริการตัวอักษรพิมพ์เล็ก ตัวพิมพ์ใหญ่ และตัวเลข (0-9) โปรแกรมนี้สุ่มอักขระ จากนั้นสร้างสตริงสุ่ม
Input: Here we are giving the string length Output: A random string of that length. Example “XSme6VAsvJ”
อัลกอริทึม
Step 1:Define array to hold all uppercase, lowercase letters and numbers Step 2: Take length n from user Step 3: Randomly choose characters’ n times and create a string of length n Step 4: End
โค้ดตัวอย่าง
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz";
int len = sizeof(alphanum) - 1;
char genRandom() { // Random string generator function.
return alphanum[rand() % len];
}
int main() {
srand(time(0));
int n;
cout << "Enter string length: ";
cin >> n;
for(int z = 0; z < n; z++) { //generate string of length n
cout << genRandom(); //get random character from the given list
}
return 0;
} ผลลัพธ์
Enter string length: 10 XSme6VAsvJ