How to get last character of 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.


For C strings, it is

String[strlen(String) - 1];

For C++ style strings, it is either

String.back();
*String.rbegin();
String[String.length() - 1];

Use the back() function for std::string:

std::string str ("Some string");
cout << str.back()

Output:

g

You can use the function:

my_string.back();

If you want to output it, then:

#include <iostream>
std::cout << my_string.back();

Tags:

C++

String