Boost String Algorithms Library

The Boost String Algorithms library is another relatively simple library that fills in important and everyday functionality that is missing from the C++ standard template library (STL), in this, the algorithms for processing strings. A typical usage snippet looks something like the following:

// Get some option from the user
std::string o = get_user_option();
// Normalise by converting all options to upper case
std::string norm = boost::to_upper_copy(std::string(o));
// Process....

The functionality provided by the Boost String Library is similar to that offered in most modern interpret languages, such as ''Python'' or ''Perl'', and may be divided into the following categories:

  • Lower-case / Upper-case conversion and testing
  • White-space handling
  • Simple sub-string searching and find-and-replace
  • Simple string splitting

The obvious advantage of using this library is that there is no simple, light-weight C++ alternative, while using functions from the standard ''C'' library is very error prone and inflexible. Further more, because the strings algorithm library is build on top of the Boost.Range library it allows for particularly clear and flexible syntax, for example:

std::string s ("Test string");
std::vector<char> s2 = boost::assign::list_of('T')('e')('s')('t');

// Process normal string
boost::to_upper(s);
// Process vector of characters
boost::to_upper(s2);
// Process vector defined by pair of iterators
boost::iterator_range<std::vector<char>::iterator>
  r(boost::make_iterator_range(s2.begin(), s2.end()));
boost::to_upper(r);

Finally, here is a complete very simple program that converts the input line-by-line to upper-case characters:

#include <iostream>
#include <string>
#include <boost/algorithm/string/case_conv.hpp>

// Convert line-by-line to upper case
void convert(std::istream &ins,
             std::ostream &os)
{
  std::string cline;
  while(ins.good())
  {
    std::getline(ins,cline);
    boost::to_upper(cline);
    os<<cline;
  }
}


int main(int argc, const char **argv)
{
  convert(std::cin,
          std::cout);
}