fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <unordered_map>
  4.  
  5. std::string replaceVariables(std::string input, std::unordered_map<std::string, std::string>& variables) {
  6. std::size_t start = input.find("%");
  7. while (start != std::string::npos) {
  8. std::size_t end = input.find("%", start + 1);
  9. std::string key = input.substr(start + 1, end - start - 1);
  10.  
  11. // Check if value also contains variables
  12. auto it = variables.find(key);
  13. if (it != variables.end()) {
  14. std::string value = it->second;
  15. value = replaceVariables(value, variables);
  16. input.replace(start, end - start + 1, value);
  17. }
  18. else {
  19. input.replace(start, end - start + 1, key);
  20. }
  21.  
  22. start = input.find("%", end);
  23. }
  24. return input;
  25. }
  26.  
  27. int main() {
  28. std::unordered_map<std::string, std::string> variables = {
  29. {"USER", "%XX%-admin"},
  30. {"HOME", "/%USER%/home"},
  31. {"XX", "YY"}
  32. };
  33.  
  34. std::string input = "I am %USER% My home is %HOME%";
  35. std::string output = replaceVariables(input, variables);
  36.  
  37. std::cout << output << std::endl;
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
I am YY-admin My home is /YY-admin/home