C++ : Split String By Separator

This code show a simple method how to split string in C++. The output from this code split string in C++ are in vector<string>. Please check Split String in C++ below :

#include <vector>
#include <iostream>
#include <string>
using namespace std;
vector<string> splitString(string str, string separator)
{
	vector<string> result;
	string tmp;
	int start, end;
	
	result.clear();
    start = 0;
    end = str.find(separator);
    while (end != string::npos)
    {
        tmp = str.substr(start, end - start);
		result.push_back(tmp);
		
        start = end + separator.length();
        end = str.find(separator, start);
    }

    tmp = str.substr(start, end);
	result.push_back(tmp);
	
	return(result);
}

int main(int argc, char **argv)
{
	vector<string> result;
	string str = "where are you now ?";
	string separator = " ";
	result = splitString(str, separator);
	for(int i=0; i<(int) result.size(); i++)
		cout<<result[i]<<endl;
	return(0);
}

Save that file to split_string.cpp. Compile code using command :

g++ split_string.cpp -o split_string

Running split string in C++ by command :

C:\temp\listdir>split_string.exe
where
are
you
now
?
Source :
http://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c

Add a Comment

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.