get a word from specified location in a string

Hello everyone
this my first topic in this forum so i hope u like it :).
during my last programming task i came through a little challenge that is how to get a word from a string giving it's location.
e.x: "This should be fun" so what if i want to get the word number 3 "be" from this string.
the upcoming code will help u solve this problem i hope:).

1
2
3
4
5
6
7
8
9
10
string tokenizer(string str,int wordNum)
{
	string word; // Temp storage
	word = strtok((char*)str.c_str(), " "); //the default delimiter is " " 
	for(int i = 1; i < wordNum; i++)
	{
		word = strtok(NULL, " ");
	}
	return word;
}


the other overloaded version will give u the option to identify the delimiter by yourself
1
2
3
4
5
6
7
8
9
10
11
string tokenizer(string str,int wordNum, string delim)
{
	string word;
	word = strtok((char*)str.c_str(), delim.c_str());
	for(int i = 1; i < wordNum; i++)
	{
		word = strtok(NULL, delim.c_str());
	}

	return word;
}


the last overloaded version will return the number of words so if we give it the example above and the delimiter is space it will return 4 words.

1
2
3
4
5
6
7
8
9
10
11
12
13
int tokenizer(string str, string delim)
{
	char* word;
	int i = 0;
	word = strtok((char*)str.c_str(), delim.c_str());
	while (word != NULL)
	{
		word = strtok(NULL, delim.c_str());
		i++;
	}

	return i;
}


this code rely on the strtok method from the c library
http://www.cplusplus.com/reference/clibrary/cstring/strtok/

some of u may not like using strtok() so this code can be slightly altered and use the find() method instead of strtok()

have fun people :)
Errr.... so you are asking ppl to play with your "assignment" or you are asking for alternative solutions to the "assignment" ?
no i am giving a solution for a problem i faced and maybe some one will need it to and in this code you will notice it's kinda hybird between c++ and c library and i have noticed some ppl don't like that so i am telling them the find method may work as a alternative solution and use pure c++ llibrary only
Yeah, you definitely should not use strtok() on the return value of std::string()::c_str().

Topic archived. No new replies allowed.