C++ 字符串连接

字符串连接

+ 运算符可用于字符串之间,将它们添加在一起以形成新字符串。这称为串联(concatenation):

实例

string firstName = "Bill ";
string lastName = "Gates";
string fullName = firstName + lastName;
cout << fullName;

亲自试一试

在上面的例子中,我们在 firstName 后面添加了一个空格,以便在输出时在 BillGates 之间创建一个空格。然而,您也可以通过添加带有引号的空格(" "' ')来实现:

实例

string firstName = "Bill";
string lastName = "Gates";
string fullName = firstName + " " + lastName;
cout << fullName;

亲自试一试

附加

在 C++ 中,字符串实际上是一个对象,其中包含了可以对字符串执行某些操作的函数。例如,您也可以使用 append() 函数来连接字符串:

实例

string firstName = "Bill ";
string lastName = "Gates";
string fullName = firstName.append(lastName);
cout << fullName;

亲自试一试

提示:请在我们的字符串函数参考手册中查看其他有用的字符串函数。