c++

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

小亿
135
2023-12-07 00:44:58
栏目: 编程语言

在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后面。最后,我们分别使用++=操作符的结果输出连接后的字符串。

0
看了该问题的人还看了