fork(14) download
  1. #include <cstddef>
  2. #include <algorithm>
  3. #include <iostream>
  4. #include <iterator>
  5. #include <string>
  6.  
  7. void sanitize(std::string &stringValue)
  8. {
  9. // Add backslashes.
  10. for (auto i = stringValue.begin();;) {
  11. auto const pos = std::find_if(
  12. i, stringValue.end(),
  13. [](char const c) { return '\\' == c || '\'' == c || '"' == c; }
  14. );
  15. if (pos == stringValue.end()) {
  16. break;
  17. }
  18. i = std::next(stringValue.insert(pos, '\\'), 2);
  19. }
  20.  
  21. // Removes others.
  22. stringValue.erase(
  23. std::remove_if(
  24. stringValue.begin(), stringValue.end(), [](char const c) {
  25. return '\n' == c || '\r' == c || '\0' == c || '\x1A' == c;
  26. }
  27. ),
  28. stringValue.end()
  29. );
  30. }
  31.  
  32. int main()
  33. {
  34. std::string s = "hello\" \"wo'rld\\ this is\na test";
  35. std::cout << s << "\n---\n";
  36. sanitize(s);
  37. std::cout << s << "\n---\n";
  38. }
  39.  
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
hello" "wo'rld\ this is
a test
---
hello\" \"wo\'rld\\ this isa test
---