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:

  1. Include Necessary Headers:
  2. #include <iostream>: Included for input/output operations.
  3. #include <string>: Included for string handling operations.

  4. Declare Standard Namespace:

  5. The using namespace std; statement allows us to use elements of the std namespace without explicitly qualifying them with std::.

  6. Main Function:

  7. The main function serves as the entry point of the program.

  8. Initialize the String:

  9. string str = "Hello, World!";: Initializes a string variable str with the value "Hello, World!".

  10. Get Last Character:

  11. char lastChar = str.back();: Uses the back() function of the std::string class to obtain the last character of the string str.

  12. Output the Result:

  13. cout << "The last character of the string is: " << lastChar << endl;: Outputs the last character of the string to the console.

  14. Return Statement:

  15. return 0;: Indicates successful execution of the program.