Created
July 20, 2025 18:32
-
-
Save Lokno/20418f293948518ee9bc081aa3b38749 to your computer and use it in GitHub Desktop.
C++ static function which will replace envionment variable name denoted by a prefix and corresponding postfix
This file contains hidden or 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
// Replace environment variables identified by a prefix and postfix string with their corresponding values | |
// Returns a new modified string or the original string if it encounters incorrect formatted input | |
static std::string ResolveEnvVars(const std::string& str, const std::string prefix, const std::string postfix) | |
{ | |
size_t p = 0; | |
size_t a = std::string::npos; | |
size_t b = std::string::npos; | |
std::string outstr = str; | |
bool found = true; | |
bool error = false; | |
while (found) | |
{ | |
found = false; | |
a = outstr.find(prefix, p); | |
if (a != std::string::npos) | |
{ | |
b = outstr.find(postfix, a + prefix.length()); | |
if (b != std::string::npos) | |
{ | |
std::string varname = outstr.substr(a + prefix.length(), b - a - prefix.length()); | |
char* varvalue = std::getenv(varname.c_str()); | |
if (varvalue != NULL) | |
{ | |
outstr.replace(a, b - a + postfix.length(), varvalue); | |
p += a + std::strlen(varvalue); | |
found = true; | |
} | |
else error = true; | |
} | |
else error = true; | |
} | |
} | |
return error ? str : outstr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment