Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the tail of a std::string?

Tags:

c++

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.

like image 253
Ronald McBean Avatar asked Sep 29 '11 12:09

Ronald McBean


People also ask

What does std::string end () return?

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.

What does string back () return?

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.

How do I find a character in a string C++?

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.


3 Answers

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); 
like image 64
Matthieu M. Avatar answered Sep 19 '22 08:09

Matthieu M.


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!)

like image 33
CharlesB Avatar answered Sep 21 '22 08:09

CharlesB


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.

like image 27
Benoit Avatar answered Sep 20 '22 08:09

Benoit