Trim Strings in Cpp with Boost
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).
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|