Search code examples
c++algorithmparsingboostboost-tokenizer

Can boost::split Be Used on a List of Only One Token?


I would like to iterate over a comma-separated list of strings and do things with each string. Is there a way to set boost::split to recognize both "abc,xyz" and "abc" as valid inputs? In other words, can Split return the entire input string if it the predicate doesn't match anything?

Or should I be using boost:tokenizer instead?


Solution

  • Boost 1.54 does exactly what you want. Haven't tried newer versions.

    Example:

    #include <iostream>
    #include <string>
    #include <vector>
    #include <boost/algorithm/string.hpp>
    
    int main()
    {
      std::string test1 = "abc,xyz";
      std::vector<std::string> result1;
      boost::algorithm::split(result1, test1, boost::is_any_of(","));
      for (auto const & s : result1)
      {
        std::cout << s << std::endl;
      }
    
      std::string test2 = "abc";
      std::vector<std::string> result2;
      boost::algorithm::split(result2, test2, boost::is_any_of(","));
      for (auto const & s : result2)
      {
        std::cout << s << std::endl;
      }
    
      return 0;
    }
    

    Produces:

    abc
    xyz
    abc