C++ STD find_last_of not working?

c++, std, string

Solution

The problem is the second argument to `substr` - it's supposed to be a count of the number of characters in the substring. That means you should do:

return str.substr(first, last - first + 1);

Make sure you always read the documentation for a function you're using (perhaps until you know it off by heart).

Problem

I'm trying to write a function that cleans a string from preceeding or trailing whitespaces. So basically, if you pass it the function `" \tHello, this is a test! \t"` then it will must return `"Hello, this is a test!"`. Here's my code, but... ``` string clean_str(string str) { const string alphabet("abcdefghijklmnopqrstuvwxyz1234567890åäö-"); size_t first = str.find_first_of(alphabet); size_t last = str.find_last_of(alphabet); return str.substr(first, last); } int _tmain(int argc, _TCHAR* argv[]) { string s(" test 123-4 "); cout << "[" << clean_str(s) << "]"; Sleep(INFINITE); return 0; } ``` It returns ``` // s == "test 123-4 " ``` Which is wrong. I've decided to go with Boost anyway, but I still want to know why this doesn't work. Thanks.

Original source