Thinking in C++

My C++ code snips.

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;
	
	while(flag)
	{
		pos=str.find_first_of(ch,pos);
		if(pos == string::npos)
		{
			flag = false;
			pos = str.size();
		}
		sub = str.substr(old_pos,pos-old_pos);  // Disregard the '.'
		v_str.push_back(sub);
		old_pos = ++pos;
	}
}

Usage:

#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.

	splitString(v_str,str,ch);

	for(vector<string>::iterator iter= v_str.begin();iter!=v_str.end();++iter)
		cout<<*iter<<"\n";
	return 0;
}

Output:

How
Are
You

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

About these ads

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:

WordPress.com Logo

You are commenting using your WordPress.com 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

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: