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

   2025-02-13 5370
核心提示:在C++中,可以使用+操作符或+=操作符将两个字符串连接起来。下面是使用这两种方法的示例代码:#include iostream#include string

在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 WorldResult using += operator: Hello World

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言