Get the last element of a std::string

C++String

C++ Problem Overview


I was wondering if there's an abbreviation or a more elegant way of getting the last character of a string like in:

char lastChar = myString.at( myString.length() - 1 );

Something like myString.back() doesn't seem to exist. Is there an equivalent?

C++ Solutions


Solution 1 - C++

In C++11 and beyond, you can use the back member function:

char ch = myStr.back();

In C++03, std::string::back is not available due to an oversight, but you can get around this by dereferencing the reverse_iterator you get back from rbegin:

char ch = *myStr.rbegin();

In both cases, be careful to make sure the string actually has at least one character in it! Otherwise, you'll get undefined behavior, which is a Bad Thing.

Hope this helps!

Solution 2 - C++

You probably want to check the length of the string first and do something like this:

if (!myStr.empty())
{
    char lastChar = *myStr.rbegin();
}

Solution 3 - C++

You could write a function template back that delegates to the member function for ordinary containers and a normal function that implements the missing functionality for strings:

template <typename C>
typename C::reference back(C& container)
{
    return container.back();
}

template <typename C>
typename C::const_reference back(const C& container)
{
    return container.back();
}

char& back(std::string& str)
{
    return *(str.end() - 1);
}

char back(const std::string& str)
{
    return *(str.end() - 1);
}

Then you can just say back(foo) without worrying whether foo is a string or a vector.

Solution 4 - C++

*(myString.end() - 1) maybe? That's not exactly elegant either.

A python-esque myString.at(-1) would be asking too much of an already-bloated class.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDeveView Question on Stackoverflow
Solution 1 - C++templatetypedefView Answer on Stackoverflow
Solution 2 - C++Kerri BrownView Answer on Stackoverflow
Solution 3 - C++fredoverflowView Answer on Stackoverflow
Solution 4 - C++tenpnView Answer on Stackoverflow