📜  C++示例 Char数组转换为C++中的字符串(1)

📅  最后修改于: 2023-12-03 15:14:04.496000             🧑  作者: Mango

Char数组转换为C++中的字符串

在C++编程中,我们经常会需要将一个字符数组转换为字符串类型。下面介绍常见的几种方法。

1. 使用std::string的构造函数

当我们需要将一个char数组转换为字符串类型的时候,可以使用std::string的构造函数。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    char char_array[] = "hello world";
    string str = string(char_array);
    cout << str << endl; // 输出 hello world
    return 0;
}
2. 使用std::stringstream

另一种方法是使用std::stringstream来进行转换。

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    char char_array[] = "hello world";
    stringstream ss;
    ss << char_array;
    string str = ss.str();
    cout << str << endl; // 输出 hello world
    return 0;
}
3. 使用strcpy函数

除了上述方法,我们还可以使用strcpy函数来将char数组拷贝到一个字符串中。

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    char char_array[] = "hello world";
    char str[100];
    strcpy(str, char_array);
    cout << str << endl; // 输出 hello world
    return 0;
}

以上就是常见的char数组转换为字符串类型的几种方法。具体选择哪种方法可以根据实际情况进行选择。