How to split a string

27 01 2009




Sometimes we need to split a long sentence by some delimiter values. Or consider a situation like, we have a sentence and we need to split it into words. That is we need to split the sentence by spaces.




There have different methods to do this. I would like share one of the efficient method among them. Please look on the following code snippet, its using some standard STL functions to accomplish this.




#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
void SplitMyString()
   string strDelimiter = _T(" ");
   string strSplitMe   = _T("Miles to go before I sleep...");
   const vector<string> SplittedWords = CustomStringSplitter( strSplitMe, strDelimiter );
   vector<string>::const_iterator  itrBegin(SplittedWords.begin());
   vector<string>::const_iterator  itrEnd(SplittedWords.end());
   //just check the result
   for(; itrBegin != itrEnd; ++itrBegin)
      string s1( *itrBegin );     
vector<string> CustomStringSplitter(const string& p_strSplitMe, const string& p_strDelimiter) {
   vector<string> vectResult;
   //iterator getting the starting point of the string
   string::const_iterator itrStart = p_strSplitMe.begin(), itrSubStart;
   while (true) {
      //iterator getting the position of the 1st element that matches the delimiter
      itrSubStart = search( itrStart, p_strSplitMe.end(), p_strDelimiter.begin(), p_strDelimiter.end());
      //getting the words
      string temp(itrStart, itrSubStart);
      //pushing the words into a vector
      if ( !temp.empty()) {
      //end of the sentence reached
      if (itrSubStart == p_strSplitMe.end()) {
      //iterator removing the parsed word from the sentence
      itrStart = itrSubStart + p_strDelimiter.size();
   //now the vector contains words
   return vectResult;



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: