The +
operator can be used between strings to add them together to make a new string. This is called concatenation:
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
Try it Yourself »
In the example above, we added a space after firstName to create a space between John and Doe on output. However, you could also add a space with quotes (" "
or ' '
):
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName;
Try it Yourself »
A string in C++ is actually an object, which contain functions that can perform certain operations on strings. For example, you can also concatenate strings with the append()
function:
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName.append(lastName);
cout << fullName;
Try it Yourself »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!