Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Trim

 

Trim is a std::string code snippet to remove leading and trailing whitespace from a std::string.

 

 

 

 

 

Stl Trim using the STL only

 

#include <string>

///Trim leading and trailing whitespace
//From http://www.richelbilderbeek.nl/CppTrim.htm
const std::string Trim(const std::string& s)
{
  const int size = s.size();
  int posBegin = -1;
  int posEnd = size-1;
  for (int i=0; i!=size; ++i)
  {
    if (s[i]!=' ' && s[i]!='\n' && s[i]!='\t')
    {
      posBegin = i; break;
    }
  }
  if (posBegin == -1) return "";
  for (int i=size-1; i!=-1; --i)
  {
    if (s[i]!=' ' && s[i]!='\n' && s[i]!='\t')
    {
      posEnd = i; break;
    }
  }

  return s.substr(posBegin,posEnd-posBegin+1);
}

 

 

 

 

 

Boost Trim using Boost

 

#include <string>
#include <boost/algorithm/string/trim.hpp>

///Trim leading and trailing whitespace
//From http://www.richelbilderbeek.nl/CppTrim.htm
const std::string Trim(const std::string& s)
{
  return boost::algorithm::trim_copy(s);
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict