Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last element of a std::string

Tags:

c++

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?

like image 607
Deve Avatar asked Feb 03 '11 09:02

Deve


People also ask

How do I get the last element of a string in C++?

You can use string. back() to get a reference to the last character in the string. The last character of the string is the first character in the reversed string, so string. rbegin() will give you an iterator to the last character.

How do you find the last element of a string?

If we want to get the last character of the String in Java, we can perform the following operation by calling the "String. chatAt(length-1)" method of the String class. For example, if we have a string as str="CsharpCorner", then we will get the last character of the string by "str. charAt(11)".

How do you find the last index of a character in a string in C++?

The std::string::find_last_of is a string class member function which is used to find the index of last occurrence of any characters in a string. If the character is present in the string then it returns the index of the last occurrence of that character in the string else it returns string::npos.

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.


1 Answers

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!

like image 88
templatetypedef Avatar answered Oct 04 '22 12:10

templatetypedef