实现跨平台的实现随机长度的字符串获取,两种方法:
随机字符串实现1:??
std::random_device rd;
std::mt19937 generator(rd());
std::string get_uuid(int len)
{
std::string out;
int flag = 0, i = 0;
for (i = 0; i < len - 1; i++)
{
flag = get_rand_num() % 3;
switch (flag)
{
case 0:
out+= 'A' + get_rand_num() % 26;
break;
case 1:
out += 'a' + get_rand_num() % 26;
break;
case 2:
out += '0' + get_rand_num() % 10;
break;
default:
out += 'x';
break;
}
}
return out;
}
unsigned int get_rand_num()
{
return generator();
}
int get_rand_range(int i_min, int i_max)
{
if (i_min >= i_max)
{
return get_rand_num();
}
return i_min + (int)(get_rand_num() % (i_max - i_min));
}
随机字符串实现2:?
std::random_device rd;
std::mt19937 generator(rd());
std::string get_random_string(const int randomStringLength)
{
const std::string possibleCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
std::string randomString;
for (int i = 0; i < randomStringLength; ++i)
{
int index = generator() % possibleCharacters.length();
char nextChar = possibleCharacters.at(index);
randomString = randomString + nextChar;
}
return randomString;
}
|