HomeC&C++WainTutorialsSamplesTip & TrickTools


To split a string into sub-parts is a frequent task in C++, so a simple splitter function might be handy.
But before showing you the code we have to agree on how we define a part. Lets consider the string: "Volvo;;200;230.23", if the delimiter is ; will the string then contain three or four parts? In other words, is the second part a empty string or not? The function below will split the string in four parts, the second is empty.
Another issue is whether the function should be allowed to modify the original string. The following function will, so you might have to save a copy of the original string.
bool Split(std::string &aDest, std::string &aSrc, char aDelim)
{
   if(aSrc.empty())
      return false;
   std::string::size_type pos = aSrc.find(aDelim);
   aDest = aSrc.substr(0, pos);
   if(pos != std::string::npos)
     aSrc = aSrc.substr(pos + 1);
   else
     aSrc = "";

   return true;
}
aDest is the destination string, aSrc is the source, aDelim is the delimiter, it will return true if there is more input.
To use it:
int main()
{
   std::string Test = "Volvo;;200;230.23";
   std::string Sub;
   while(Split(Sub, Test, ';'))
     std::cout << Sub << std::endl;
}
Don't forget to include iostream and string.
And now a slightly more advanced string splitter, it differs from the other in that:
1: It does not destroy the input.
2: You can have more that one delimiter character.
3: Multible delimiters after each other do not form seperate tokens, if comma is the delimiter, the string ",John,,,Smith,," contains two sub-strings, "John" and "Smith".
class StrSplitterClass
{
public:
   StrSplitterClass(const std::string &aSrc) :
      Src(aSrc),
      StartPos(0)
   {}
   bool Get(std::string &aDest, const char *aDelim)
   {
      if(StartPos == std::string::npos)
         return false;
      StartPos = Src.find_first_not_of(aDelim, StartPos);
      if(StartPos != std::string::npos)
      {
         std::string::size_type EndPos;
         EndPos = Src.find_first_of(aDelim, StartPos);
         aDest = Src.substr(StartPos, EndPos - StartPos);
         StartPos = EndPos;
         return true;
      }
      return false;
   }
   void Set(const std::string aSrc)
   {
      Src = aSrc;
      StartPos = 0;
   }
private:
   StrSplitterClass(); // Not used
   std::string Src;
   std::string::size_type StartPos;
};
You can use it this way:
int main()
{
   StrSplitterClass StrSplitter("..Ole.,.Hansen..");

   std::string S;
   while(StrSplitter.Get(S, ".,"))
      std::cout << "[" << S << "]" << std::endl;

   std::string Test = "John Smith";
   StrSplitter.Set(Test);
   while(StrSplitter.Get(S, " "))
      std::cout << "[" << S << "]" << std::endl;
}