David David - 1 year ago 36
C++ Question

C++, best way to change a string at a particular index

I want to change a C++ string at a particular index like this:

string s = "abc";
s[1] = 'a';

Is the following code valid? Is this an acceptable way to do this?

I didn't find any reference which says it is valid:


Which says that through "overloaded [] operator in string" we can perform the write operation.

Answer Source

Yes, the following C++ program:

#include <iostream>

int main() {
    std::string s = "abc";
    s[1] = 'a';
    std::cout << s;

prints aac. You risk accidentally writing to un-assigned memory if string s is blankstring. C++ will let you do that and it leads to undefined behaviour.

The safe way to do this would be to use string::replace: http://cplusplus.com/reference/string/string/replace