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

Assigning a character to an std::string at an index will produce the correct result, for example:

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

For those of you below doubting my IDE/library setup, see jdoodle demo: http://jdoodle.com/ia/ljR, and screenshot: https://i.stack.imgur.com/Adav3.jpg

Which prints aac. The drawback is you risk accidentally writing to un-assigned memory if string s is blankstring or you write too far. C++ will gladly write off the end of the string, and that causes undefined behavior.

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

For example

#include <iostream> 
int main() { 
    std::string s = "What kind of king do you think you'll be?"; 
    std::string s2 = "A good king?"; 
    //       pos len str_repl 
    s.replace(40, 1, s2); 
    std::cout << s;   
    //prints: What kind of king do you think you'll beA good king?
}

The replace function takes the string s, and at position 40, replaced one character, a questionmark, with the string s2. If the string is blank or you assign something out of bounds, then there’s no undefined behavior.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)