fork download
  1. #include <iostream>
  2. #include <algorithm>
  3.  
  4. inline bool not_space(char c){
  5. return c != ' ' && ( 9 > c || c > 13 );
  6. }
  7.  
  8. inline bool my_isspace(char c){
  9. return std::isspace(static_cast<unsigned char>(c));
  10. }
  11.  
  12. template<typename FN>
  13. auto find_if(std::string & s, FN fn){
  14. return std::find_if(s.begin(), s.end(), fn);
  15. }
  16. template<typename FN>
  17. auto rfind_if(std::string & s, FN fn){
  18. return std::find_if(s.rbegin(), s.rend(), fn).base();
  19. }
  20.  
  21. inline void ltrim(std::string &s) {
  22. s.erase(s.begin(), find_if(s, not_space));
  23. }
  24.  
  25. inline void rtrim(std::string &s) {
  26. s.erase(rfind_if(s, not_space), s.end());
  27. }
  28.  
  29. // modify a copy
  30. std::string trim(std::string const& s){
  31. std::string t{s};
  32. ltrim(t);
  33. rtrim(t);
  34. return t;
  35. }
  36.  
  37. // modify a move
  38. std::string trim(std::string&& s){
  39. ltrim(s);
  40. rtrim(s);
  41. return s;
  42. }
  43.  
  44. int main(){
  45. std::string s{" abc "};
  46. std::cout << trim(s) << '\n'; // copy
  47. std::string ss{" def "};
  48. std::cout << trim(std::move(ss)) << '\n'; // move
  49. std::string const t{" xyz "};
  50. std::cout << trim(t) << '\n'; // copy
  51. std::cout << '"' << trim(" sdf ") << '"'; // move
  52. }
  53.  
Success #stdin #stdout 0.01s 5304KB
stdin
Standard input is empty
stdout
abc
def
xyz
"sdf"