字符和字符串的字符串串联

string concatenation of character and string

本文关键字:字符串 字符      更新时间:2023-10-16
#include <bits/stdc++.h>
using namespace std;
int main() 
{
string s1 = "Alice";
s1 +='';
s1 +='';
cout << s1.size() << endl;         // output: 7
string s2 = "Alice";
s2 += "";
s2 += "";
cout << s2.size() << endl;         // output: 5
}

这是怎么回事?

请解释单引号和双引号在串联中的作用之间的区别。

s1 +='';

将字符添加到s1,而不考虑字符是什么。

s2 += "";

将一个以空值结尾的字符串添加到s2。因此,出于该函数的目的,RHS 的嵌入空字符被视为字符串终止符。从本质上讲,这相当于

s2 += "";

这解释了您观察到的输出差异。

可以使用std::string::append追加char const*对象的嵌入空字符。

s2.append("", 1);