Prv*_*dav 0 c++ string string-concatenation c++11
我正在使用c++11。当我使用+=运算符来压缩字符串或字符时,它不起作用,但是=起作用。
例如,我独立地(即分别使用了以下所有测试用例)。
string s="abdddddd";
string ss="";
ss+=s[0];//working
ss+=s[0]+s[1]; //not working output: Ã
ss+="hi"+s[2]; //not working no output
ss+='d'+'c'; //not working output: ?
ss+="hi"+"string"; //not working error: invalid operands of types ‘const char [3]’ and ‘const char [7]’ to binary ‘operator+’
string another="this";
ss+=another+'b'; //working
ss+="hi"+another;//working
ss+=("hi"+s[3]); //not working
ss=ss+"hi"+s[3]; //working
ss=ss+"hi"+"this"; //working
Run Code Online (Sandbox Code Playgroud)
另外添加括号也不起作用。所以,我想知道为什么它不能与字符串一起使用,而是可以与整数相加。
您的问题不是+=,而是+。
例如,在线路ss+=s[0]+s[1];,s[0]和s[1]是类型char。添加它们将添加其整数表示形式(ASCII码),并将此总和表示的字符连接起来ss。
在中ss+='d'+'c';,您会看到相同的提示,在此处您char显式地给出了文字。
仅使用+来连接std::string带std::string或一个std::string一个字符或字符串文字。您不能将两个字符串文字或两个字符或一个字符串文字与一个字符连接在一起。(在所有这些情况下,+其语义都不同于字符串连接,或者甚至不是有效的语法。)