How to split std::string in C++

  • 0
  • May 29, 2016

There’re a lot of funny and clumsy answer about this question, some of them even convert string to char* and then using strtok to accomplish it.

But here, I figure out a very nice way just using the find function in string class.

void Split_String(std::string& input_str, std::string& delimiter){
	std::string substring;
	std::string::size_type offset;
	std::string::size_type old_offset;
	offset = 0;
	old_offset = 0;

		offset = input_str.find(delimiter.c_str(), old_offset);
		if(offset == input_str.npos)
			substring = input_str.substr(old_offset,
				input_str.length() - old_offset);
			//The substring here will be the last part of input_str
			//You can process it here, do some comparison or etc.
			break; //Jump out the loop

		substring = input_str.substr(old_offset, offset - old_offset);
		//This is every part in input_str but last part
		//You can process it here, do some comparison or etc.

		old_offset = offset + delimiter.length();



Leave a Reply