c++ get last character of string
Code to Get Last Character of a String in C++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
char lastChar = str.back();
cout << "The last character of the string is: " << lastChar << endl;
return 0;
}
Explanation:
- Include Necessary Headers:
#include <iostream>
: Included for input/output operations.#include <string>
: Included for string handling operations.Declare Standard Namespace:
The
using namespace std;
statement allows us to use elements of thestd
namespace without explicitly qualifying them withstd::
.Main Function:
The
main
function serves as the entry point of the program.Initialize the String:
string str = "Hello, World!";
: Initializes a string variablestr
with the value "Hello, World!".Get Last Character:
char lastChar = str.back();
: Uses theback()
function of thestd::string
class to obtain the last character of the stringstr
.Output the Result:
cout << "The last character of the string is: " << lastChar << endl;
: Outputs the last character of the string to the console.Return Statement:
return 0;
: Indicates successful execution of the program.