Replace part of a string with another string

前端 未结 15 2326
终归单人心
终归单人心 2020-11-22 02:54

Is it possible in C++ to replace part of a string with another string?

Basically, I would like to do this:

QString string(\"hello $name\");
string.re         


        
15条回答
  •  你的背包
    2020-11-22 03:43

    Yes, you can do it, but you have to find the position of the first string with string's find() member, and then replace with it's replace() member.

    string s("hello $name");
    size_type pos = s.find( "$name" );
    if ( pos != string::npos ) {
       s.replace( pos, 5, "somename" );   // 5 = length( $name )
    }
    

    If you are planning on using the Standard Library, you should really get hold of a copy of the book The C++ Standard Library which covers all this stuff very well.

提交回复
热议问题