fork download
  1. #include <string>
  2. #include <iostream>
  3.  
  4. int main() {
  5. std::string to_search = "Some data with %MACROS to substitute";
  6. std::string replace_with = "some very nice macros";
  7. std::string macro_name;
  8.  
  9. std::cout << "Before: " << to_search << '\n';
  10.  
  11. std::string::size_type pos = 0;
  12. while ((pos = to_search.find('%', pos)) != std::string::npos)
  13. {
  14. // Permit uppercase letters, lowercase letters and numbers in macro names
  15. auto after = to_search.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", pos + 1);
  16.  
  17. // if no matching chars, set after past the last char...
  18. if (after == std::string::npos)
  19. after = to_search.size();
  20.  
  21. auto count = after - pos;
  22. if (count > 1)
  23. {
  24. // extract the macro name and replace the macor only if
  25. // the name actually maps to something worth replacing...
  26.  
  27. macro_name = to_search.substr(pos + 1, count - 1);
  28. if (macro_name == "MACROS")
  29. {
  30. // found a macro!
  31. to_search.replace(pos, count, replace_with);
  32.  
  33. // start the next search after the replaced text...
  34. pos += replace_with.size();
  35.  
  36. continue;
  37. }
  38.  
  39. // check for other macros as needed...
  40. }
  41.  
  42. // no matching macro, skip the '%' and search again from the next char...
  43. ++pos;
  44. }
  45.  
  46. std::cout << "After: " << to_search << '\n';
  47. }
Success #stdin #stdout 0s 15232KB
stdin
Standard input is empty
stdout
Before: Some data with %MACROS to substitute
After: Some data with some very nice macros to substitute