C++ Split String Every X Characters

The heart of the algorithm really comes down to the following two lines.

for (size_t i = 0; i < s.size(); i += l)
    res.push_back(s.substr(i, l));

Also, you should pass the string by const reference.


This will split a string into a vector. If there aren't an even number of splits, it will add the extra characters to the end.

std::vector<std::string> Split(const std::string& str, int splitLength)
{
   int NumSubstrings = str.length() / splitLength;
   std::vector<std::string> ret;

   for (auto i = 0; i < NumSubstrings; i++)
   {
        ret.push_back(str.substr(i * splitLength, splitLength));
   }

   // If there are leftover characters, create a shorter item at the end.
   if (str.length() % splitLength != 0)
   {
        ret.push_back(str.substr(splitLength * NumSubstrings));
   }


   return ret;
}

Using that std::string is a collection of char, a simple implementation could be :

std::vector<std::string> DIFSplitStringByNumber(const std::string & str, int len)
{
    std::vector<std::string> entries;
    for(std::string::const_iterator it(str.begin()); it != str.end();)
    {
        int nbChar = std::min(len,(int)std::distance(it,str.end()));
        entries.push_back(std::string(it,it+nbChar));
        it=it+nbChar;
    };
    return entries;
}

Live sample