Last active
December 28, 2020 12:21
-
-
Save NikolasK-source/00edef2a78177ccdc2d62f18b25793e9 to your computer and use it in GitHub Desktop.
C++ "random" string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <random> | |
#include <string> | |
#include <ctime> | |
namespace RandomString { | |
static constexpr const char* DEFAULT_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; | |
static std::default_random_engine random{static_cast<unsigned>(time(0))}; | |
static std::mt19937 random_generator(random()); | |
std::string generate(size_t length, const std::string& charset = "") { | |
// use default charset if no charset is specified | |
std::string str = charset.empty() ? std::string(DEFAULT_CHARSET) : charset; | |
// double string length until it is at least as long as the requested length | |
while(length > str.length()) str += str; | |
// shuffle string | |
std::shuffle(str.begin(), str.end(), random_generator); | |
// return substring with specified length | |
return str.substr(0, length); | |
} | |
} // namespace RandomString |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment