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?
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.
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)".
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.
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.
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!
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