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?
Printable View
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.Quote:
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.Quote:
Originally Posted by lazyme
By the way, why did you not test before asking?
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.Quote:
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.
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();
}
}
}
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 :)