Feb 202013
 

Recently I have been using the Boost C++ library to perform some string manipulations in the programs that I write. The functions included in Boost are so useful that I wanted to share some of the ones that I like the most.

  • split (and trim_copy)
    The Boost string algorithm library contains many routines that are found in scripting languages but that are not included in the C++ standard library. A good example is extracting all the words in a string containing words separated by spaces.
    The following bit of code trims all the leading and trailing spaces in the string line

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    #include <boost/algorithm/string.hpp>
     
    using namespace std;
    using namespace boost; // trim_copy, split, and is_any_of are contained in the boost namespace
     
    // Trim spaces so that later we can split properly
    string trimmed_line = trim_copy(line);
    // Create a vector of strings
    vector<string> split_string;
    // Split the words in the string line when one or more spaces are found
    split(split_string, trimmed_line, is_any_of(" "), token_compress_on );

    So if line = "C 0.000 0.000 1.000" then the code above will give split_string = {"C", "0.000", "0.000", "1.000"}.

  • format
    I am a big fan of format because it offers a printf-style syntax and is string-friendly. The output of format can be directed to a stream via <<, but I find myself using it mostly as a string and so I use the utility function str to convert the output of format:

    1
    2
    3
    4
    5
    6
    7
    8
    
    #include <boost/format.hpp>
     
    using namespace std;
    using namespace boost; // format is contained in the boost namespace
     
    double x = 19.2224;
    double y = 127.001;
    string formatted_double = str(format("%12.9f %12.9f") % x % y);
  • join
    Boost join is a useful function to join strings placing a separator between them:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    #include <boost/algorithm/string/join.hpp>
     
    using namespace std;
    using namespace boost; // join is contained in the boost namespace
     
    std::vector<std::string> list;
    list.push_back("3");
    list.push_back("5");
    list.push_back("7");
    std::string joined = boost::algorithm::join(list, ",");
    std::cout << joined << std::endl;  // will print "3,5,7"
 February 20, 2013  Programming

Sorry, the comment form is closed at this time.