简体   繁体   中英

string concatenation of character and string

#include <bits/stdc++.h>
using namespace std;

int main() 
{
    string s1 = "Alice";
    s1 +='\0';
    s1 +='\0';
    cout << s1.size() << endl;         // output: 7

    string s2 = "Alice";
    s2 += "\0";
    s2 += "\0";
    cout << s2.size() << endl;         // output: 5
}

What is wrong here?

Please explain the difference between role of single quotes and double quotes in concatenation.

s1 +='\0';

adds the character to s1 regardless of what the character is.

s2 += "\0";

adds a null terminated string to s2 . Because of that, the embedded null character of the RHS is seen as a string terminator for the purposes of that function. In essence, that is equivalent to

s2 += "";

That explains the difference in output that you observed.

You can use std::string::append to append embedded null characters of a char const* object.

s2.append("\0", 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM