• 9
• 10
• 9
• 10
• 10
• entries
97
98
• views
50699

# Data structures

200 views

I'm taking a data structures class this semester and I quite like it. The programs, for me at least, have been really easy (queues, and a hash table implementation), others in the class seem to be struggling somewhat. This isn't to brag, but a lot of them seem to think that they can code up anything an hour before it's due and of course, most of them don't make it.

Ah well, I started on the next project today, which I should have done rather soon since I can reuse a lot of the code from the previous project, just implementing a different data structure. Today I coded up a small parser that I was happy with to sort of tokenize a string into its various parts.

Given a string with the following format:

data1;data2;etc.

the function returns each part. It seems to me that there would be ways already implemented to do this sort of thing with strings, but I haven't found it. It was a nice exercise at least. I'm sure it's not the most efficient, but it's easy to use and gets the job done. If you can use it, by all means, have at it.

string getToken(string& initial, char delim){	string temp = "";	int length = (int)initial.size();	for(int i=0; i	{		temp += initial.at(i);		if(initial.at(i) == delim)		{			initial.erase(0, i+1);			temp.erase(i, 1);			return temp;		}	}	return temp;}

Can I suggest you to use the std::string::find() method ? It seems to be what you are looking for :)

#include <algorithm>
#include <string>

std::string getToken(std::string& initial, char delim)
{
std::string result;
// find the position of the next delimiter. One can also
// try to cope with more delimiters using std::string::find_first_of()
std::string::size_type position = initial.find(delim);
// don't care if the position is std::string::npos because
// if there is no delimiter, then we copy everything into result
result = initial.substr(0, position);
// remove the used characters from the initial string
if (position == std::string::npos) {
// we are eating all the string in this case (no delimiter found)
initial = "";
} else {
// we eat every used characters - including the delimiter
initial.erase(initial.begin(), initial.begin()+position+1);
}
return result;
}



Also, std::string::find_first_of() and std::string::find_last_of() are very useful for this kind of stuff. I like to use find_last_of to strip the extensions off filenames.

Thanks for the suggestions, i'll try them out later on. [smile]