How to retrieve the tail of a std::string
?
If wishes could come true, it would work like that:
string tailString = sourceString.right(6);
But this seems to be too easy, and doesn't work...
Any nice solution available?
Optional question: How to do it with the Boost string algorithm library?
ADDED:
The method should be save even if the original string is smaller than 6 chars.
std::string::end Returns an iterator pointing to the past-the-end character of the string. The past-the-end character is a theoretical character that would follow the last character in the string.
std::string::back() in C++ with Examples This function returns a direct reference to the last character of the string. This shall only be used on non-empty strings.
string find in C++String find is used to find the first occurrence of sub-string in the specified string being called upon. It returns the index of the first occurrence of the substring in the string from given starting position. The default value of starting position is 0.
There is one caveat to be aware of: if substr is called with a position past the end of the array (superior to the size), then an out_of_range
exception is thrown.
Therefore:
std::string tail(std::string const& source, size_t const length) { if (length >= source.size()) { return source; } return source.substr(source.size() - length); } // tail
You can use it as:
std::string t = tail(source, 6);
Using the substr()
method and the size()
of the string, simply get the last part of it:
string tail = source.substr(source.size() - 6);
For handling case of a string smaller than the tail size see Benoit's answer (and upvote it, I don't see why I get 7 upvotes while Benoit provides a more complete answer!)
You could do:
std::string tailString = sourceString.substr((sourceString.length() >= 6 ? sourceString.length()-6 : 0), std::string::npos);
Note that npos
is the default argument, and might be omitted. If your string has a size that 6 exceeds, then this routine will extract the whole string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With