Trim whitespace from a String












17















I know there are several ways to do this in Java and C that are nice, but in C++ I can't seem to find a way to easily implement a string trimming function.



This is what I currently have:



string trim(string& str)
{
size_t first = str.find_first_not_of(' ');
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last-first+1));
}


but whenever I try and call



trim(myString);


I get the compiler error



/tmp/ccZZKSEq.o: In function `song::Read(std::basic_ifstream<char, 
std::char_traits<char> >&, std::basic_ifstream<char, std::char_traits<char> >&, char const*, char const*)':
song.cpp:(.text+0x31c): undefined reference to `song::trim(std::string&)'
collect2: error: ld returned 1 exit status


I am trying to find a simple and standard way of trimming leading and trailing whitespace from a string without it taking up 100 lines of code, and I tried using regex, but could not get that to work as well.



I also cannot use Boost.










share|improve this question

























  • Is song a namespace? Is it a class?

    – K-ballo
    Sep 14 '14 at 0:57






  • 1





    possible duplicate of Removing leading and trailing spaces from a string

    – Anderson Green
    Sep 14 '14 at 0:57






  • 3





    This question is not really to do with trimming, but with the linking error. Probably you get the same error regardless of the definition of trim

    – Brandin
    Sep 14 '14 at 0:58


















17















I know there are several ways to do this in Java and C that are nice, but in C++ I can't seem to find a way to easily implement a string trimming function.



This is what I currently have:



string trim(string& str)
{
size_t first = str.find_first_not_of(' ');
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last-first+1));
}


but whenever I try and call



trim(myString);


I get the compiler error



/tmp/ccZZKSEq.o: In function `song::Read(std::basic_ifstream<char, 
std::char_traits<char> >&, std::basic_ifstream<char, std::char_traits<char> >&, char const*, char const*)':
song.cpp:(.text+0x31c): undefined reference to `song::trim(std::string&)'
collect2: error: ld returned 1 exit status


I am trying to find a simple and standard way of trimming leading and trailing whitespace from a string without it taking up 100 lines of code, and I tried using regex, but could not get that to work as well.



I also cannot use Boost.










share|improve this question

























  • Is song a namespace? Is it a class?

    – K-ballo
    Sep 14 '14 at 0:57






  • 1





    possible duplicate of Removing leading and trailing spaces from a string

    – Anderson Green
    Sep 14 '14 at 0:57






  • 3





    This question is not really to do with trimming, but with the linking error. Probably you get the same error regardless of the definition of trim

    – Brandin
    Sep 14 '14 at 0:58
















17












17








17


10






I know there are several ways to do this in Java and C that are nice, but in C++ I can't seem to find a way to easily implement a string trimming function.



This is what I currently have:



string trim(string& str)
{
size_t first = str.find_first_not_of(' ');
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last-first+1));
}


but whenever I try and call



trim(myString);


I get the compiler error



/tmp/ccZZKSEq.o: In function `song::Read(std::basic_ifstream<char, 
std::char_traits<char> >&, std::basic_ifstream<char, std::char_traits<char> >&, char const*, char const*)':
song.cpp:(.text+0x31c): undefined reference to `song::trim(std::string&)'
collect2: error: ld returned 1 exit status


I am trying to find a simple and standard way of trimming leading and trailing whitespace from a string without it taking up 100 lines of code, and I tried using regex, but could not get that to work as well.



I also cannot use Boost.










share|improve this question
















I know there are several ways to do this in Java and C that are nice, but in C++ I can't seem to find a way to easily implement a string trimming function.



This is what I currently have:



string trim(string& str)
{
size_t first = str.find_first_not_of(' ');
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last-first+1));
}


but whenever I try and call



trim(myString);


I get the compiler error



/tmp/ccZZKSEq.o: In function `song::Read(std::basic_ifstream<char, 
std::char_traits<char> >&, std::basic_ifstream<char, std::char_traits<char> >&, char const*, char const*)':
song.cpp:(.text+0x31c): undefined reference to `song::trim(std::string&)'
collect2: error: ld returned 1 exit status


I am trying to find a simple and standard way of trimming leading and trailing whitespace from a string without it taking up 100 lines of code, and I tried using regex, but could not get that to work as well.



I also cannot use Boost.







c++ string whitespace trim






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 23 '17 at 20:40









Joulukuusi

2,15762847




2,15762847










asked Sep 14 '14 at 0:54









kf.kf.

4371520




4371520













  • Is song a namespace? Is it a class?

    – K-ballo
    Sep 14 '14 at 0:57






  • 1





    possible duplicate of Removing leading and trailing spaces from a string

    – Anderson Green
    Sep 14 '14 at 0:57






  • 3





    This question is not really to do with trimming, but with the linking error. Probably you get the same error regardless of the definition of trim

    – Brandin
    Sep 14 '14 at 0:58





















  • Is song a namespace? Is it a class?

    – K-ballo
    Sep 14 '14 at 0:57






  • 1





    possible duplicate of Removing leading and trailing spaces from a string

    – Anderson Green
    Sep 14 '14 at 0:57






  • 3





    This question is not really to do with trimming, but with the linking error. Probably you get the same error regardless of the definition of trim

    – Brandin
    Sep 14 '14 at 0:58



















Is song a namespace? Is it a class?

– K-ballo
Sep 14 '14 at 0:57





Is song a namespace? Is it a class?

– K-ballo
Sep 14 '14 at 0:57




1




1





possible duplicate of Removing leading and trailing spaces from a string

– Anderson Green
Sep 14 '14 at 0:57





possible duplicate of Removing leading and trailing spaces from a string

– Anderson Green
Sep 14 '14 at 0:57




3




3





This question is not really to do with trimming, but with the linking error. Probably you get the same error regardless of the definition of trim

– Brandin
Sep 14 '14 at 0:58







This question is not really to do with trimming, but with the linking error. Probably you get the same error regardless of the definition of trim

– Brandin
Sep 14 '14 at 0:58














5 Answers
5






active

oldest

votes


















36














Your code is fine. What you are seeing is a linker issue.



If you put your code in a single file like this:



#include <iostream>
#include <string>

using namespace std;

string trim(const string& str)
{
size_t first = str.find_first_not_of(' ');
if (string::npos == first)
{
return str;
}
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last - first + 1));
}

int main() {
string s = "abc ";
cout << trim(s);

}


then do g++ test.cc and run a.out, you will see it works.



You should check if the file that contains the trim function is included in the link stage of your compilation process.






share|improve this answer





















  • 3





    Does it handle "" or " " correctly?

    – AlexD
    Sep 14 '14 at 1:17






  • 4





    This gives crashes on empty string!

    – Stepan Yakovenko
    Nov 14 '15 at 18:58






  • 3





    Add 'if (first == string::npos) return "";' to avoid crashing. Besides this it is nice and simple solution. I saw how people using boost (!!!) to implement such things.

    – user6416335
    Jul 22 '16 at 15:11













  • string trim(string str) is more move-friendly function signature

    – yanpas
    May 24 '18 at 13:17



















19














Here is how you can do it:



std::string & trim(std::string & str)
{
return ltrim(rtrim(str));
}


And the supportive functions are implemeted as:



std::string & ltrim(std::string & str)
{
auto it2 = std::find_if( str.begin() , str.end() , (char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
str.erase( str.begin() , it2);
return str;
}

std::string & rtrim(std::string & str)
{
auto it1 = std::find_if( str.rbegin() , str.rend() , (char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
str.erase( it1.base() , str.end() );
return str;
}


And once you've all these in place, you can write this as well:



std::string trim_copy(std::string const & str)
{
auto s = str;
return ltrim(rtrim(s));
}


Try this






share|improve this answer





















  • 1





    +1 for introducing the locale which I miss from so many of the other answers around. Not neccessary the correct one as it depends on the application case, but still an important factor when dealing with strings.

    – Rado
    Aug 30 '17 at 11:14



















5














I think that substr() throws an exception if str only contains the whitespace.



I would modify it to the following code:



string trim(string& str)
{
size_t first = str.find_first_not_of(' ');
if (first == std::string::npos)
return "";
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last-first+1));
}





share|improve this answer


























  • This should be right answer

    – user6416335
    Jul 22 '16 at 15:12











  • This doesn't work for tabs or other kinds of whitespace besides spaces.

    – jocull
    Sep 29 '17 at 19:21











  • @jocull - you are right, but i think its obvious what to do to specify more whitespaces, find_first_not_of(" tnrvf")

    – Martin
    Feb 6 '18 at 9:38





















0














#include <vector>
#include <numeric>
#include <sstream>
#include <iterator>

void Trim(std::string& inputString)
{
std::istringstream stringStream(inputString);
std::vector<std::string> tokens((std::istream_iterator<std::string>(stringStream)), std::istream_iterator<std::string>());

inputString = std::accumulate(std::next(tokens.begin()), tokens.end(),
tokens[0], // start with first element
(std::string a, std::string b) { return a + " " + b; });
}





share|improve this answer































    0














    In addition to answer of @gjha:



    inline std::string ltrim_copy(const std::string& str)
    {
    auto it = std::find_if(str.cbegin(), str.cend(),
    (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    return std::string(it, str.cend());
    }

    inline std::string rtrim_copy(const std::string& str)
    {
    auto it = std::find_if(str.crbegin(), str.crend(),
    (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    return it == str.crend() ? std::string() : std::string(str.cbegin(), ++it.base());
    }

    inline std::string trim_copy(const std::string& str)
    {
    auto it1 = std::find_if(str.cbegin(), str.cend(),
    (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    if (it1 == str.cend()) {
    return std::string();
    }
    auto it2 = std::find_if(str.crbegin(), str.crend(),
    (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
    return it2 == str.crend() ? std::string(it1, str.cend()) : std::string(it1, ++it2.base());
    }





    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f25829143%2ftrim-whitespace-from-a-string%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      36














      Your code is fine. What you are seeing is a linker issue.



      If you put your code in a single file like this:



      #include <iostream>
      #include <string>

      using namespace std;

      string trim(const string& str)
      {
      size_t first = str.find_first_not_of(' ');
      if (string::npos == first)
      {
      return str;
      }
      size_t last = str.find_last_not_of(' ');
      return str.substr(first, (last - first + 1));
      }

      int main() {
      string s = "abc ";
      cout << trim(s);

      }


      then do g++ test.cc and run a.out, you will see it works.



      You should check if the file that contains the trim function is included in the link stage of your compilation process.






      share|improve this answer





















      • 3





        Does it handle "" or " " correctly?

        – AlexD
        Sep 14 '14 at 1:17






      • 4





        This gives crashes on empty string!

        – Stepan Yakovenko
        Nov 14 '15 at 18:58






      • 3





        Add 'if (first == string::npos) return "";' to avoid crashing. Besides this it is nice and simple solution. I saw how people using boost (!!!) to implement such things.

        – user6416335
        Jul 22 '16 at 15:11













      • string trim(string str) is more move-friendly function signature

        – yanpas
        May 24 '18 at 13:17
















      36














      Your code is fine. What you are seeing is a linker issue.



      If you put your code in a single file like this:



      #include <iostream>
      #include <string>

      using namespace std;

      string trim(const string& str)
      {
      size_t first = str.find_first_not_of(' ');
      if (string::npos == first)
      {
      return str;
      }
      size_t last = str.find_last_not_of(' ');
      return str.substr(first, (last - first + 1));
      }

      int main() {
      string s = "abc ";
      cout << trim(s);

      }


      then do g++ test.cc and run a.out, you will see it works.



      You should check if the file that contains the trim function is included in the link stage of your compilation process.






      share|improve this answer





















      • 3





        Does it handle "" or " " correctly?

        – AlexD
        Sep 14 '14 at 1:17






      • 4





        This gives crashes on empty string!

        – Stepan Yakovenko
        Nov 14 '15 at 18:58






      • 3





        Add 'if (first == string::npos) return "";' to avoid crashing. Besides this it is nice and simple solution. I saw how people using boost (!!!) to implement such things.

        – user6416335
        Jul 22 '16 at 15:11













      • string trim(string str) is more move-friendly function signature

        – yanpas
        May 24 '18 at 13:17














      36












      36








      36







      Your code is fine. What you are seeing is a linker issue.



      If you put your code in a single file like this:



      #include <iostream>
      #include <string>

      using namespace std;

      string trim(const string& str)
      {
      size_t first = str.find_first_not_of(' ');
      if (string::npos == first)
      {
      return str;
      }
      size_t last = str.find_last_not_of(' ');
      return str.substr(first, (last - first + 1));
      }

      int main() {
      string s = "abc ";
      cout << trim(s);

      }


      then do g++ test.cc and run a.out, you will see it works.



      You should check if the file that contains the trim function is included in the link stage of your compilation process.






      share|improve this answer















      Your code is fine. What you are seeing is a linker issue.



      If you put your code in a single file like this:



      #include <iostream>
      #include <string>

      using namespace std;

      string trim(const string& str)
      {
      size_t first = str.find_first_not_of(' ');
      if (string::npos == first)
      {
      return str;
      }
      size_t last = str.find_last_not_of(' ');
      return str.substr(first, (last - first + 1));
      }

      int main() {
      string s = "abc ";
      cout << trim(s);

      }


      then do g++ test.cc and run a.out, you will see it works.



      You should check if the file that contains the trim function is included in the link stage of your compilation process.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 20 '16 at 22:33









      Martin

      6,07685065




      6,07685065










      answered Sep 14 '14 at 1:02









      Anthony KongAnthony Kong

      15.6k2496176




      15.6k2496176








      • 3





        Does it handle "" or " " correctly?

        – AlexD
        Sep 14 '14 at 1:17






      • 4





        This gives crashes on empty string!

        – Stepan Yakovenko
        Nov 14 '15 at 18:58






      • 3





        Add 'if (first == string::npos) return "";' to avoid crashing. Besides this it is nice and simple solution. I saw how people using boost (!!!) to implement such things.

        – user6416335
        Jul 22 '16 at 15:11













      • string trim(string str) is more move-friendly function signature

        – yanpas
        May 24 '18 at 13:17














      • 3





        Does it handle "" or " " correctly?

        – AlexD
        Sep 14 '14 at 1:17






      • 4





        This gives crashes on empty string!

        – Stepan Yakovenko
        Nov 14 '15 at 18:58






      • 3





        Add 'if (first == string::npos) return "";' to avoid crashing. Besides this it is nice and simple solution. I saw how people using boost (!!!) to implement such things.

        – user6416335
        Jul 22 '16 at 15:11













      • string trim(string str) is more move-friendly function signature

        – yanpas
        May 24 '18 at 13:17








      3




      3





      Does it handle "" or " " correctly?

      – AlexD
      Sep 14 '14 at 1:17





      Does it handle "" or " " correctly?

      – AlexD
      Sep 14 '14 at 1:17




      4




      4





      This gives crashes on empty string!

      – Stepan Yakovenko
      Nov 14 '15 at 18:58





      This gives crashes on empty string!

      – Stepan Yakovenko
      Nov 14 '15 at 18:58




      3




      3





      Add 'if (first == string::npos) return "";' to avoid crashing. Besides this it is nice and simple solution. I saw how people using boost (!!!) to implement such things.

      – user6416335
      Jul 22 '16 at 15:11







      Add 'if (first == string::npos) return "";' to avoid crashing. Besides this it is nice and simple solution. I saw how people using boost (!!!) to implement such things.

      – user6416335
      Jul 22 '16 at 15:11















      string trim(string str) is more move-friendly function signature

      – yanpas
      May 24 '18 at 13:17





      string trim(string str) is more move-friendly function signature

      – yanpas
      May 24 '18 at 13:17













      19














      Here is how you can do it:



      std::string & trim(std::string & str)
      {
      return ltrim(rtrim(str));
      }


      And the supportive functions are implemeted as:



      std::string & ltrim(std::string & str)
      {
      auto it2 = std::find_if( str.begin() , str.end() , (char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
      str.erase( str.begin() , it2);
      return str;
      }

      std::string & rtrim(std::string & str)
      {
      auto it1 = std::find_if( str.rbegin() , str.rend() , (char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
      str.erase( it1.base() , str.end() );
      return str;
      }


      And once you've all these in place, you can write this as well:



      std::string trim_copy(std::string const & str)
      {
      auto s = str;
      return ltrim(rtrim(s));
      }


      Try this






      share|improve this answer





















      • 1





        +1 for introducing the locale which I miss from so many of the other answers around. Not neccessary the correct one as it depends on the application case, but still an important factor when dealing with strings.

        – Rado
        Aug 30 '17 at 11:14
















      19














      Here is how you can do it:



      std::string & trim(std::string & str)
      {
      return ltrim(rtrim(str));
      }


      And the supportive functions are implemeted as:



      std::string & ltrim(std::string & str)
      {
      auto it2 = std::find_if( str.begin() , str.end() , (char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
      str.erase( str.begin() , it2);
      return str;
      }

      std::string & rtrim(std::string & str)
      {
      auto it1 = std::find_if( str.rbegin() , str.rend() , (char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
      str.erase( it1.base() , str.end() );
      return str;
      }


      And once you've all these in place, you can write this as well:



      std::string trim_copy(std::string const & str)
      {
      auto s = str;
      return ltrim(rtrim(s));
      }


      Try this






      share|improve this answer





















      • 1





        +1 for introducing the locale which I miss from so many of the other answers around. Not neccessary the correct one as it depends on the application case, but still an important factor when dealing with strings.

        – Rado
        Aug 30 '17 at 11:14














      19












      19








      19







      Here is how you can do it:



      std::string & trim(std::string & str)
      {
      return ltrim(rtrim(str));
      }


      And the supportive functions are implemeted as:



      std::string & ltrim(std::string & str)
      {
      auto it2 = std::find_if( str.begin() , str.end() , (char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
      str.erase( str.begin() , it2);
      return str;
      }

      std::string & rtrim(std::string & str)
      {
      auto it1 = std::find_if( str.rbegin() , str.rend() , (char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
      str.erase( it1.base() , str.end() );
      return str;
      }


      And once you've all these in place, you can write this as well:



      std::string trim_copy(std::string const & str)
      {
      auto s = str;
      return ltrim(rtrim(s));
      }


      Try this






      share|improve this answer















      Here is how you can do it:



      std::string & trim(std::string & str)
      {
      return ltrim(rtrim(str));
      }


      And the supportive functions are implemeted as:



      std::string & ltrim(std::string & str)
      {
      auto it2 = std::find_if( str.begin() , str.end() , (char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
      str.erase( str.begin() , it2);
      return str;
      }

      std::string & rtrim(std::string & str)
      {
      auto it1 = std::find_if( str.rbegin() , str.rend() , (char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
      str.erase( it1.base() , str.end() );
      return str;
      }


      And once you've all these in place, you can write this as well:



      std::string trim_copy(std::string const & str)
      {
      auto s = str;
      return ltrim(rtrim(s));
      }


      Try this







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Aug 18 '15 at 11:13

























      answered Apr 27 '15 at 9:59









      gjhagjha

      1,318925




      1,318925








      • 1





        +1 for introducing the locale which I miss from so many of the other answers around. Not neccessary the correct one as it depends on the application case, but still an important factor when dealing with strings.

        – Rado
        Aug 30 '17 at 11:14














      • 1





        +1 for introducing the locale which I miss from so many of the other answers around. Not neccessary the correct one as it depends on the application case, but still an important factor when dealing with strings.

        – Rado
        Aug 30 '17 at 11:14








      1




      1





      +1 for introducing the locale which I miss from so many of the other answers around. Not neccessary the correct one as it depends on the application case, but still an important factor when dealing with strings.

      – Rado
      Aug 30 '17 at 11:14





      +1 for introducing the locale which I miss from so many of the other answers around. Not neccessary the correct one as it depends on the application case, but still an important factor when dealing with strings.

      – Rado
      Aug 30 '17 at 11:14











      5














      I think that substr() throws an exception if str only contains the whitespace.



      I would modify it to the following code:



      string trim(string& str)
      {
      size_t first = str.find_first_not_of(' ');
      if (first == std::string::npos)
      return "";
      size_t last = str.find_last_not_of(' ');
      return str.substr(first, (last-first+1));
      }





      share|improve this answer


























      • This should be right answer

        – user6416335
        Jul 22 '16 at 15:12











      • This doesn't work for tabs or other kinds of whitespace besides spaces.

        – jocull
        Sep 29 '17 at 19:21











      • @jocull - you are right, but i think its obvious what to do to specify more whitespaces, find_first_not_of(" tnrvf")

        – Martin
        Feb 6 '18 at 9:38


















      5














      I think that substr() throws an exception if str only contains the whitespace.



      I would modify it to the following code:



      string trim(string& str)
      {
      size_t first = str.find_first_not_of(' ');
      if (first == std::string::npos)
      return "";
      size_t last = str.find_last_not_of(' ');
      return str.substr(first, (last-first+1));
      }





      share|improve this answer


























      • This should be right answer

        – user6416335
        Jul 22 '16 at 15:12











      • This doesn't work for tabs or other kinds of whitespace besides spaces.

        – jocull
        Sep 29 '17 at 19:21











      • @jocull - you are right, but i think its obvious what to do to specify more whitespaces, find_first_not_of(" tnrvf")

        – Martin
        Feb 6 '18 at 9:38
















      5












      5








      5







      I think that substr() throws an exception if str only contains the whitespace.



      I would modify it to the following code:



      string trim(string& str)
      {
      size_t first = str.find_first_not_of(' ');
      if (first == std::string::npos)
      return "";
      size_t last = str.find_last_not_of(' ');
      return str.substr(first, (last-first+1));
      }





      share|improve this answer















      I think that substr() throws an exception if str only contains the whitespace.



      I would modify it to the following code:



      string trim(string& str)
      {
      size_t first = str.find_first_not_of(' ');
      if (first == std::string::npos)
      return "";
      size_t last = str.find_last_not_of(' ');
      return str.substr(first, (last-first+1));
      }






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Aug 10 '18 at 22:37









      Aubin

      11.3k64566




      11.3k64566










      answered Oct 14 '15 at 9:49









      MartinMartin

      5113




      5113













      • This should be right answer

        – user6416335
        Jul 22 '16 at 15:12











      • This doesn't work for tabs or other kinds of whitespace besides spaces.

        – jocull
        Sep 29 '17 at 19:21











      • @jocull - you are right, but i think its obvious what to do to specify more whitespaces, find_first_not_of(" tnrvf")

        – Martin
        Feb 6 '18 at 9:38





















      • This should be right answer

        – user6416335
        Jul 22 '16 at 15:12











      • This doesn't work for tabs or other kinds of whitespace besides spaces.

        – jocull
        Sep 29 '17 at 19:21











      • @jocull - you are right, but i think its obvious what to do to specify more whitespaces, find_first_not_of(" tnrvf")

        – Martin
        Feb 6 '18 at 9:38



















      This should be right answer

      – user6416335
      Jul 22 '16 at 15:12





      This should be right answer

      – user6416335
      Jul 22 '16 at 15:12













      This doesn't work for tabs or other kinds of whitespace besides spaces.

      – jocull
      Sep 29 '17 at 19:21





      This doesn't work for tabs or other kinds of whitespace besides spaces.

      – jocull
      Sep 29 '17 at 19:21













      @jocull - you are right, but i think its obvious what to do to specify more whitespaces, find_first_not_of(" tnrvf")

      – Martin
      Feb 6 '18 at 9:38







      @jocull - you are right, but i think its obvious what to do to specify more whitespaces, find_first_not_of(" tnrvf")

      – Martin
      Feb 6 '18 at 9:38













      0














      #include <vector>
      #include <numeric>
      #include <sstream>
      #include <iterator>

      void Trim(std::string& inputString)
      {
      std::istringstream stringStream(inputString);
      std::vector<std::string> tokens((std::istream_iterator<std::string>(stringStream)), std::istream_iterator<std::string>());

      inputString = std::accumulate(std::next(tokens.begin()), tokens.end(),
      tokens[0], // start with first element
      (std::string a, std::string b) { return a + " " + b; });
      }





      share|improve this answer




























        0














        #include <vector>
        #include <numeric>
        #include <sstream>
        #include <iterator>

        void Trim(std::string& inputString)
        {
        std::istringstream stringStream(inputString);
        std::vector<std::string> tokens((std::istream_iterator<std::string>(stringStream)), std::istream_iterator<std::string>());

        inputString = std::accumulate(std::next(tokens.begin()), tokens.end(),
        tokens[0], // start with first element
        (std::string a, std::string b) { return a + " " + b; });
        }





        share|improve this answer


























          0












          0








          0







          #include <vector>
          #include <numeric>
          #include <sstream>
          #include <iterator>

          void Trim(std::string& inputString)
          {
          std::istringstream stringStream(inputString);
          std::vector<std::string> tokens((std::istream_iterator<std::string>(stringStream)), std::istream_iterator<std::string>());

          inputString = std::accumulate(std::next(tokens.begin()), tokens.end(),
          tokens[0], // start with first element
          (std::string a, std::string b) { return a + " " + b; });
          }





          share|improve this answer













          #include <vector>
          #include <numeric>
          #include <sstream>
          #include <iterator>

          void Trim(std::string& inputString)
          {
          std::istringstream stringStream(inputString);
          std::vector<std::string> tokens((std::istream_iterator<std::string>(stringStream)), std::istream_iterator<std::string>());

          inputString = std::accumulate(std::next(tokens.begin()), tokens.end(),
          tokens[0], // start with first element
          (std::string a, std::string b) { return a + " " + b; });
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 29 '17 at 14:10









          WillWill

          11




          11























              0














              In addition to answer of @gjha:



              inline std::string ltrim_copy(const std::string& str)
              {
              auto it = std::find_if(str.cbegin(), str.cend(),
              (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
              return std::string(it, str.cend());
              }

              inline std::string rtrim_copy(const std::string& str)
              {
              auto it = std::find_if(str.crbegin(), str.crend(),
              (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
              return it == str.crend() ? std::string() : std::string(str.cbegin(), ++it.base());
              }

              inline std::string trim_copy(const std::string& str)
              {
              auto it1 = std::find_if(str.cbegin(), str.cend(),
              (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
              if (it1 == str.cend()) {
              return std::string();
              }
              auto it2 = std::find_if(str.crbegin(), str.crend(),
              (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
              return it2 == str.crend() ? std::string(it1, str.cend()) : std::string(it1, ++it2.base());
              }





              share|improve this answer






























                0














                In addition to answer of @gjha:



                inline std::string ltrim_copy(const std::string& str)
                {
                auto it = std::find_if(str.cbegin(), str.cend(),
                (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
                return std::string(it, str.cend());
                }

                inline std::string rtrim_copy(const std::string& str)
                {
                auto it = std::find_if(str.crbegin(), str.crend(),
                (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
                return it == str.crend() ? std::string() : std::string(str.cbegin(), ++it.base());
                }

                inline std::string trim_copy(const std::string& str)
                {
                auto it1 = std::find_if(str.cbegin(), str.cend(),
                (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
                if (it1 == str.cend()) {
                return std::string();
                }
                auto it2 = std::find_if(str.crbegin(), str.crend(),
                (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
                return it2 == str.crend() ? std::string(it1, str.cend()) : std::string(it1, ++it2.base());
                }





                share|improve this answer




























                  0












                  0








                  0







                  In addition to answer of @gjha:



                  inline std::string ltrim_copy(const std::string& str)
                  {
                  auto it = std::find_if(str.cbegin(), str.cend(),
                  (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
                  return std::string(it, str.cend());
                  }

                  inline std::string rtrim_copy(const std::string& str)
                  {
                  auto it = std::find_if(str.crbegin(), str.crend(),
                  (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
                  return it == str.crend() ? std::string() : std::string(str.cbegin(), ++it.base());
                  }

                  inline std::string trim_copy(const std::string& str)
                  {
                  auto it1 = std::find_if(str.cbegin(), str.cend(),
                  (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
                  if (it1 == str.cend()) {
                  return std::string();
                  }
                  auto it2 = std::find_if(str.crbegin(), str.crend(),
                  (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
                  return it2 == str.crend() ? std::string(it1, str.cend()) : std::string(it1, ++it2.base());
                  }





                  share|improve this answer















                  In addition to answer of @gjha:



                  inline std::string ltrim_copy(const std::string& str)
                  {
                  auto it = std::find_if(str.cbegin(), str.cend(),
                  (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
                  return std::string(it, str.cend());
                  }

                  inline std::string rtrim_copy(const std::string& str)
                  {
                  auto it = std::find_if(str.crbegin(), str.crend(),
                  (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
                  return it == str.crend() ? std::string() : std::string(str.cbegin(), ++it.base());
                  }

                  inline std::string trim_copy(const std::string& str)
                  {
                  auto it1 = std::find_if(str.cbegin(), str.cend(),
                  (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
                  if (it1 == str.cend()) {
                  return std::string();
                  }
                  auto it2 = std::find_if(str.crbegin(), str.crend(),
                  (char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
                  return it2 == str.crend() ? std::string(it1, str.cend()) : std::string(it1, ++it2.base());
                  }






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 2 at 1:31

























                  answered Jan 2 at 1:26









                  ivan.ukrivan.ukr

                  829519




                  829519






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f25829143%2ftrim-whitespace-from-a-string%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      MongoDB - Not Authorized To Execute Command

                      How to fix TextFormField cause rebuild widget in Flutter

                      in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith