C++ Replace third letter in string

I have a c++ string and I want to replace the third letter of the string with the letter ‘a’. I have seen many tutorials explaining how to replace all instances of a character in a string but I would like to replace the third letter, no matter what the character is. I am also new to c++ and still learning and I cant find any tutorials on this. How can I achieve this?

Code for the string:

   string str = "apple banana";

The final output should be

apale banana

>Solution :

You can easily achieve it with replace() method,

#include <iostream>
#include <string>
using namespace std;

int main()
{
    // Declare the String
    string str = "apple banana";
    
    
    str.replace(2, 1, "a");
    cout << str <<endl;
    
    return 0;
}

Leave a Reply