#include <iostream>
#include <string>
#include <unordered_map>
std::string replaceVariables(std::string input, std::unordered_map<std::string, std::string>& variables) {
std::size_t start = input.find("%");
while (start != std::string::npos) {
std::size_t end = input.find("%", start + 1);
std::string key = input.substr(start + 1, end - start - 1);
// Check if value also contains variables
auto it = variables.find(key);
if (it != variables.end()) {
std::string value = it->second;
value = replaceVariables(value, variables);
input.replace(start, end - start + 1, value);
}
else {
input.replace(start, end - start + 1, key);
}
start = input.find("%", end);
}
return input;
}
int main() {
std::unordered_map<std::string, std::string> variables = {
{"USER", "%XX%-admin"},
{"HOME", "/%USER%/home"},
{"XX", "YY"}
};
std::string input = "I am %USER% My home is %HOME%";
std::string output = replaceVariables(input, variables);
std::cout << output << std::endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RyaW5nPgojaW5jbHVkZSA8dW5vcmRlcmVkX21hcD4KCnN0ZDo6c3RyaW5nIHJlcGxhY2VWYXJpYWJsZXMoc3RkOjpzdHJpbmcgaW5wdXQsIHN0ZDo6dW5vcmRlcmVkX21hcDxzdGQ6OnN0cmluZywgc3RkOjpzdHJpbmc+JiB2YXJpYWJsZXMpIHsKICBzdGQ6OnNpemVfdCBzdGFydCA9IGlucHV0LmZpbmQoIiUiKTsKICB3aGlsZSAoc3RhcnQgIT0gc3RkOjpzdHJpbmc6Om5wb3MpIHsKICAgIHN0ZDo6c2l6ZV90IGVuZCA9IGlucHV0LmZpbmQoIiUiLCBzdGFydCArIDEpOwogICAgc3RkOjpzdHJpbmcga2V5ID0gaW5wdXQuc3Vic3RyKHN0YXJ0ICsgMSwgZW5kIC0gc3RhcnQgLSAxKTsKICAgIAogICAgLy8gQ2hlY2sgaWYgdmFsdWUgYWxzbyBjb250YWlucyB2YXJpYWJsZXMgCiAgICBhdXRvIGl0ID0gdmFyaWFibGVzLmZpbmQoa2V5KTsKICAgIGlmIChpdCAhPSB2YXJpYWJsZXMuZW5kKCkpIHsKICAgICAgc3RkOjpzdHJpb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