Gettting the last character of a string in C++

Gettting the last character of a string in C++

In this post we will give you information about Gettting the last character of a string in C++. Hear we will give you detail about Gettting the last character of a string in C++And how to use it also give you demo for it if it is necessary.

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();

Hope this code and post will helped you for implement Gettting the last character of a string in C++. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US