Ok, I have this function that was provided by you guys, and it works, but I needed to tweak it a bit, and I can't seem to get it tweaked right. Trying to make it so it takes a 3rd parameter which takes an integer which will determine how many pieces it splits up into. For instance:

"This is a test to prove a point"

If i did this

std::vector<std::string> tokens = split("This is a test to prove a point", 
"\t\n ", 4);

It would break it into 4 pieces as follows:

This
is
a
test to prove a point

So that it includes all of the remaining into the last piece of the split. I thought I had the logic right here, but I must be missing something, i have had a long day and can't think. Some help, or tell me its not possible? Ty :)

std::vector<std::string> split(const std::string& src, const std::string& delim, int numOfSplit)
{
	using namespace std;
	vector<string> result;
	int i = 1;
	int limit = src.size();
	string::size_type startPos = 0, endPos = 0;
	do{
		endPos = src.find_first_of(delim,startPos);
		string::size_type length = endPos - startPos;
		if(length != 0)
			result.push_back( src.substr(startPos,length) );
		startPos = endPos + 1;
		i++;
	}while(i != numOfSplit);
	string::size_type length = limit - startPos;
	if(length != 0)
		result.push_back(src.substr(startPos, length));
	return result;
}

Try replacing the do{ ... }while() loop with a for loop, like:

for(unsigned i = 0; i < numOfSplit - 1; i++){
    endPos = src.find_first_of(delim,startPos);
    std::string::size_type length = endPos - startPos;
    if(length != 0)
        result.push_back( src.substr(startPos,length) );
    startPos = endPos + 1;
}

This would also fix the hole in your code that lets the loop run indefinitely if sizes 0 or 1 are used!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.