c++怎么将两个字符串连接起来

c++
600
2023/12/21 0:44:58
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,可以使用+操作符或+=操作符将两个字符串连接起来。下面是使用这两种方法的示例代码:

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello";
    std::string str2 = " World";

    // 使用+操作符
    std::string result = str1 + str2;
    std::cout << "Result using + operator: " << result << std::endl;

    // 使用+=操作符
    str1 += str2;
    std::cout << "Result using += operator: " << str1 << std::endl;

    return 0;
}

输出:

Result using + operator: Hello World
Result using += operator: Hello World

在上面的示例中,我们先定义了两个字符串str1str2,然后使用+操作符将它们连接起来并将结果赋值给result字符串。接下来,我们使用+=操作符将str2连接到str1后面。最后,我们分别使用++=操作符的结果输出连接后的字符串。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c++中strtok函数的用法是什么