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.
Unlike String Class, the StringBuilder class is used to represent a mutable string of characters and has a predefined method for change a character at a specific index – setCharAt(). Replace the character at the specific index by calling this method and passing the character and the index as the parameter.
Using 'str.replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
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://imgur.com/f21rA5R
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With