温馨提示×

如何使用c++ string库函数连接字符串

c++
小樊
81
2024-09-24 22:16:03
栏目: 编程语言

在 C++ 中,你可以使用 std::string 库中的函数来连接字符串。以下是一些常用的方法:

  1. 使用 + 运算符连接字符串:
#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello, ";
    std::string str2 = "World!";
    std::string result = str1 + str2;
    std::cout << result << std::endl; // 输出 "Hello, World!"
    return 0;
}
  1. 使用 append() 函数连接字符串:
#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello, ";
    std::string str2 = "World!";
    std::string result = str1.append(str2);
    std::cout << result << std::endl; // 输出 "Hello, World!"
    return 0;
}
  1. 使用 std::stringstream 来连接字符串:
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string str1 = "Hello, ";
    std::string str2 = "World!";
    std::stringstream ss;
    ss << str1 << str2;
    std::string result = ss.str();
    std::cout << result << std::endl; // 输出 "Hello, World!"
    return 0;
}

以上三种方法都可以实现字符串的连接。你可以根据自己的需求和喜好选择合适的方法。

0