Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

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.

like image 313
David Avatar asked Aug 19 '13 03:08

David


People also ask

How do you replace a character in a string at a specific index?

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.

How do you replace a specific character in a string?

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.


1 Answers

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.

like image 149
Eric Leschinski Avatar answered Sep 18 '22 13:09

Eric Leschinski