C++, best way to change a string at a particular index
c++, string
Solution
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.
Problem
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: http://www.cplusplus.com/reference/string/string/ Which says that through "overloaded [] operator in string" we can perform the write operation.