In this tutorial we will discuss how to use trim algorithms from C++ Boost String Algorithm Library. Let’s learn them step by step,

Boost String algorithm library provides different algorithms for string trimmings. Let’s first discuss the simple one i.e,

What if we want to trim the string of white spaces from left side or right side or from both the sides. There are 3 different algorithms for these operations:

Trim String from Both sides

template<typename SequenceT>
void trim(SequenceT &, const std::locale & = std::locale());

Output: [Start :: Hello :: End]

Trim From Left side

template<typename SequenceT>
void trim(SequenceT &, const std::locale & = std::locale());

Output: [Start :: Hello :: End   ]

Trim From Right side

template<typename SequenceT>
void trim(SequenceT &, const std::locale & = std::locale());

Output: [   Start :: Hello :: End]

Trim the copy of string

From the above its clear that all the three functions boost::algorithm::trim , boost::algorithm::trim_left , boost::algorithm::trim_right modifies the passed string by trimming them.

 

But this might not be the requirement every time suppose we don’t to modify our original string, we just want trimmed result in a new object. In such scenarios we should use different versions of above algorithms i.e.

boost::algorithm::trim_copy
boost::algorithm::trim_left_copy
boost::algorithm::trim_right_copy

Above 3 algorithms will trim the string but instead of modifying the original, the modifies a copy of it and returns that modified copy. Example usages is as follows,

Output:

[Start :: Hello :: End]
[Start :: Hello :: End   ]
[   Start :: Hello :: End]

Condition based trimming of Strings

Suppose we want to trim some other characters instead of default white spaces like,trimming colons from following string,

::StartMsg :: Hello :: EndMsg::

To achieve this we can use condition based versions of trim algorithm i.e.

boost::algorithm::trim_if()
boost::algorithm::trim_left_if()
boost::algorithm::trim_right_if()
boost::algorithm::trim_copy_if()
boost::algorithm::trim_left_copy_if()
boost::algorithm::trim_right_copy_if()

These algorithms take a unary predicate as argument it. These algorithm will keep on trimming the characters till this predicate returns true for them.

Checkout this example,

Output:

[StartMsg :: Hello :: EndMsg]
[StartMsg :: Hello :: EndMsg::]
[::StartMsg :: Hello :: EndMsg]

Complete Executable Code is as follows,