In this C++ tutorial, you shall learn how to get the first character in the given string using string::at() function, or array notation, with examples.

C++ Get last character in String

string::at() function returns the char at specified index/position from the string. So, if we need to access the last character in the string, we can pass string length - 1 as argument to at() function.

We can also use string indexing mechanism with square brackets to get the last character in string.

Syntax

The syntax of the expression to get the last character in the string str using string::at() function is

</>
Copy
str.at(str.length() - 1)

The syntax of the expression to get the last character in the string str using square brackets notation is

</>
Copy
str[str.length() - 1]

Programs

1. Get last char in string “apple” using string::at()

In the following program, we take a string in str, get the last character in str using string::at(), and print the character to console output.

main.cpp

</>
Copy
#include <iostream>
using namespace std;

int main() {
    string str = "apple";
    char lastChar = str.at(str.length() - 1);
    cout << "Last character : " << lastChar;
}

Output

Last character : e

2. Get last char in string “apple” using string[index]

In this program, we get the last character in str using square brackets notation.

main.cpp

</>
Copy
#include <iostream>
using namespace std;

int main() {
    string str = "apple";
    char lastChar = str[str.length() - 1];
    cout << "Last character : " << lastChar;
}

Output

Last character : e

Conclusion

In this C++ Tutorial, we learned how to get the last character from string using string[index] notation or string::at() function, with examples.