Deve
Deve

Reputation: 4648

Get the last element of a std::string

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?

Upvotes: 92

Views: 112901

Answers (4)

templatetypedef
templatetypedef

Reputation: 372814

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.

Upvotes: 142

fredoverflow
fredoverflow

Reputation: 263138

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.

Upvotes: 7

Kerri Brown
Kerri Brown

Reputation: 1187

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

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

Upvotes: 24

tenpn
tenpn

Reputation: 4716

*(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.

Upvotes: 2

Related Questions