Date: 2010may14
Update: 2026sep30
Language: C/C++
Level: novice
Q. C/C++: How to get the last character of a std::string
A. Like this:
char getLastChar(const std::string &s) {
if (s.length() == 0) return '\0';
return s[s.length() - 1];
}
Full Example Use:
#include <stdio.h>
#include <string>
// (Place getLastChar() from above here)
int main() {
{ // With a short std::string
std::string str = "hello world";
char c = getLastChar(str);
printf("last char of %s is %c\n", str.c_str(), c);
}
{ // With an empty std::string
std::string str;
char c = getLastChar(str);
printf("last char of <empty> is %c\n", c);
// Should print nothing without crashing
}
}
Output:
last char of hello world is d
last char of <empty> is