Gettting the last character of a string in C++
In this tutorial, we are going to learn about how to get the last character of a string in C++.
Consider, we have the following string.
string car = "benz";
Now, we want to get the last character z
from the above string.
Getting the last character
To access the last character of a string, we can use the built-in back()
function in C++
Here is an example, that gets the last character z
from the following string:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string car = "benz";
char lastCharacter = car.back(); //returns last character
cout<< lastChar;
return 0;
}
Output:
"z"
Similarly, we can use the subscript []
syntax by passing string.length()-1
which is the index of a last character.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string car = "benz";
char lastCharacter= car[car.length()-1];
cout<< lastCharacter;
return 0;
}
Note: The length() function returns the total number of characters in a given string, so we are subtracting it with
-1
to get the last character index.
or we can also use the rbegin()
function to access the last character of a string like this.
char lastCharacter = *car.rbegin();