Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading