Trim Strings in C++ with Boost Posted in Programming on 22 of Jul, 2015

One of the biggest grievances with I had when I started writing a lot of c++ code was that a lot of things that we take for granted as built in things in other (primarily dynamic) languages are all a bit harder to do (right) in c++. This means that for things like simple string manipulation you often need outside help. For the most common cases though, there is boost.

Dependencies in c++ is also bit harder than it is in e.g. php, nodejs or ruby. If you are used to just adding your dependency in a file (be it composer.json, package.json or Gemfile) you are in for a surprise. Luckily most of boost is header-only libraries - which mean that you just include a specific file, and you are off to the races.

For trimming strings there are only two header files you need to know about boost/algorithm/string/trim.hpp and boost/algorithm/string/trim_all.hpp. The first allows you to trim from either left or right side, and as either a in-place operation or on a copy. (Which you prefer depends on your use case - but I usually opt for the copy-version - as I don’t like running external library functions with side effects on my data).

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

int main() {
  std::string result;

  std::string str01 = " this is a string with something to trim   ";

  result = boost::trim_left_copy(str01);
  std::cout << "|" << result << "|" << std::endl;

  result = boost::trim_right_copy(str01);
  std::cout << "|" << result << "|" << std::endl;

  result = boost::trim_all_copy(str01);
  std::cout << "|" << result << "|" << std::endl;

  return 0;

This example shows trimming left side, trimming right side, and trimming both sides. To compile (at least on my mac) run: clang++ -std=c++0x -stdlib=libc++ test.cpp -o test and then run the newly compiled test program ./test The result of the invocation should be

|this is a string with something to trim   |
| this is a string with something to trim|
|this is a string with something to trim|