Skip to content

Instantly share code, notes, and snippets.

@NikolasK-source
Last active December 28, 2020 12:21
Show Gist options
  • Save NikolasK-source/00edef2a78177ccdc2d62f18b25793e9 to your computer and use it in GitHub Desktop.
Save NikolasK-source/00edef2a78177ccdc2d62f18b25793e9 to your computer and use it in GitHub Desktop.
C++ "random" string
#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