如何使用 C++ 建立一個隨機字母數字字串?
本節中,我們將瞭解如何使用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP