您的位置:首页 >C++中连接两个string的方法
发布于2025-10-22 阅读(0)
扫一扫,手机访问
C++中连接字符串常用+或+=操作符,示例为string str1 = "Hello"; string str2 = "World"; string result = str1 + " " + str2; 输出Hello World。

在C++中连接两个字符串(string)有多种方法,最常用的是使用 + 操作符或 += 操作符。只要字符串类型是 std::string,就可以很方便地进行拼接。
这是最直观的方法,将两个 string 对象用 + 连接,生成一个新的字符串。
示例代码:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello";
string str2 = "World";
string result = str1 + " " + str2;
cout << result << endl; // 输出:Hello World
return 0;
}
如果想把一个字符串追加到另一个字符串末尾,可以使用 += 操作符,它会修改原字符串。
示例代码:
string str1 = "Hello";
string str2 = "World";
str1 += " ";
str1 += str2;
cout << str1 << endl; // 输出:Hello World
注意:只能对至少一个是 std::string 类型的进行拼接。下面这样写是合法的:
string name = "Tom";
string greeting = "Hello, " + name + "!"; // 正确
但下面这样会出错:
"Hello, " + "World" + name // 错误:前两个是字符串字面量,不能直接相加解决办法:确保至少有一个是 string 类型,或让 std::string 出现在加法表达式中:
string greeting = string("Hello, ") + "World" + name; // 正确
std::string 提供了 append() 成员函数,也可以用来拼接字符串,功能更灵活。
示例:
string s = "Hello";
s.append(" ").append("World");
cout << s << endl; // 输出:Hello World
基本上就这些。日常使用中,+ 和 += 已经足够方便。如果涉及大量拼接,考虑使用 ostringstream 或 append 提升效率。操作不复杂,但要注意类型匹配问题。
上一篇:iPad画中画功能怎么开启
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9