If the whole string is a white space, my startPos will be 0 and endPos(length of string) will be -1. Wouldn't that truncate the string to an empty string? Or am I missing something here?
If the whole string is a white space, my startPos will be 0 and endPos(length of string) will be -1. Wouldn't that truncate the string to an empty string? Or am I missing something here?
Actually, it will be std::string::npos, which is not -1, even though it is equal to -1 converted to std::string::size_type, which is an unsigned integer type.Originally Posted by lazyme
No. It would get the substring of the string from the character at index 0 to the last character of the string.Originally Posted by lazyme
By the way, why did you not test before asking?
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Sorry, I just got a bit confused.
I have made changes to my function and I think this should work fine even when the whole string is a whitespace.
Code:if(endPos!=std::string::npos) { endPos = (endPos+1)-startPos; } else { endPos = 0; }
It looks correct now, but you should test.Originally Posted by lazyme
Now, notice that if std::string::npos is returned by find_first_not_of, it will also be be returned by find_last_not_of. This suggests that you can handle the case of a string consisting only of whitespace separately, and thus simplify your code.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Does this code look better?
Code:void trim( std::string& strToBeFormatted ) { size_t startPos = strToBeFormatted.find_first_not_of("\n\t "); size_t endPos = strToBeFormatted.find_last_not_of("\n\t "); if(startPos==std::string::npos) { startPos = 0; endPos = 0; } else { endPos = (endPos+1)-startPos; } strToBeFormatted = strToBeFormatted.substr( startPos, endPos ); }
What I had in mind:
Code:void trim(std::string& subject) { if (!subject.empty()) { std::string::size_type startPos = subject.find_first_not_of("\n\t "); if (startPos != std::string::npos) { std::string::size_type endPos = subject.find_last_not_of("\n\t "); subject = subject.substr(startPos, endPos - startPos + 1); } else { subject.clear(); } } }
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Your code definitely looks much better. I hope with more practice I would start thinking on the same lines and write better code.
Thanks laserlight