fork download
  1. #include <algorithm>
  2. #include <string>
  3. #include <iostream>
  4. #include <cctype>
  5. #include <functional>
  6.  
  7. using namespace std;
  8.  
  9. // A function object that will take a character, and append either "%20" or the
  10. // original character to our new string
  11. struct Converter
  12. {
  13. std::string* pS; // this points to our string we will build
  14.  
  15. Converter(std::string* s) : pS(s) {}
  16.  
  17. void operator()(char ch)
  18. {
  19. if ( isspace(ch) )
  20. (*pS) += "%20"; // it's a space, so replace
  21. else
  22. *pS += ch; // it is not a space, so use the same character
  23. }
  24. };
  25.  
  26. // trim spaces from end of string
  27. std::string &rtrim(std::string &s)
  28. {
  29. s.erase(std::find_if(s.rbegin(), s.rend(),
  30. std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
  31. return s;
  32. }
  33.  
  34. // function to return the new string by looping over the original string
  35. string getNewString(const std::string& s)
  36. {
  37. std::string outStr; // our new string
  38.  
  39. // loop over each character, calling our Coverter::operator()(char) function
  40. for_each(s.begin(), s.end(), Converter(&outStr));
  41. return outStr;
  42. }
  43.  
  44. int main()
  45. {
  46. string instring = "This string has spaces ";
  47. cout << getNewString(rtrim(instring));
  48. }
  49.  
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
This%20string%20has%20spaces