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

前端 未结 4 984
余生分开走
余生分开走 2020-12-24 13:02

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 a

4条回答
  •  春和景丽
    2020-12-24 13:37

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

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

    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  
    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.

提交回复
热议问题