Thinking in C++

My C++ code snips.

  • Recent Posts

  • Archives

  • Categories

  • Advertisements

C++ Split String

Posted by Abhi on February 9, 2012

Here is a simple string split function that I wrote a while back. The function takes a string such as “How.Are.You.”, a divider – “.” and a reference to a vector of strings as input. The vector is then filled with the strings after they have been split.

#include <string>
#include <vector>

using std::vector;
using std::string;

void splitString(vector<string> &v_str,const string &str,const char ch)
	string sub;
	string::size_type pos = 0;
	string::size_type old_pos = 0;
	bool flag=true;
		if(pos == string::npos)
			flag = false;
			pos = str.size();
		sub = str.substr(old_pos,pos-old_pos);  // Disregard the '.'
		old_pos = ++pos;


#include <string>
#include <vector>
#include <iostream>
#include <iterator>
#include "splitString.h"       // Header file for the splitString function.

using std::vector;
using std::string;
using std::cout;

int main()
	string str= "How.Are.You";	// String to be split.
	char ch = '.';			// The divider.
	vector<string> v_str;		// Vector to store the divided strings.


	for(vector<string>::iterator iter= v_str.begin();iter!=v_str.end();++iter)
	return 0;



Remember to put the necessary #include if you decide to put the codes in separate files.


One Response to “C++ Split String”

  1. […] C++ Split String […]

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: