remove last letter in string c++

To remove the last letter in a string in C++, you can follow these steps:

  1. Declare a string variable: Start by declaring a string variable and assigning the desired string to it. For example, std::string str = "Hello";.

  2. Get the length of the string: Use the length() or size() function to get the length of the string. For example, int len = str.length();.

  3. Remove the last character: To remove the last character from the string, you can use the erase() function. Pass the index of the last character as the starting point and specify a count of 1. For example, str.erase(len - 1, 1);.

  4. Print or use the modified string: Finally, you can print or use the modified string as needed. For example, std::cout << str;.

Here is an example that puts all the steps together:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello";
    int len = str.length();
    str.erase(len - 1, 1);
    std::cout << str;
    return 0;
}

This code will output "Hell" because the last letter 'o' has been removed from the original string "Hello".