如何在 C + + 中将字符串转换为字符数组?

我想转换 stringchar数组,但不是 char*。我知道如何将字符串转换为 char*(通过使用 malloc或我在代码中发布它的方式)-但这不是我想要的。我只是想把 string转换成 char[size]数组。有可能吗?

#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;


int main()
{
// char to string
char tab[4];
tab[0] = 'c';
tab[1] = 'a';
tab[2] = 't';
tab[3] = '\0';
string tmp(tab);
cout << tmp << "\n";


// string to char* - but thats not what I want


char *c = const_cast<char*>(tmp.c_str());
cout << c << "\n";


//string to char
char tab2[1024];
// ?


return 0;
}
620105 次浏览

只需用 strcpy将字符串复制到数组中。

尝试 strcpy () ,但正如 Fred 所说,这是 C + + ,而不是 C

我能想到的最简单的方法是:

string temp = "cat";
char tab2[1024];
strcpy(tab2, temp.c_str());

为了安全起见,你可能会选择:

string temp = "cat";
char tab2[1024];
strncpy(tab2, temp.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;

或者可以是这种方式:

string temp = "cat";
char * tab2 = new char [temp.length()+1];
strcpy (tab2, temp.c_str());

你可以像这样使用 strcpy():

strcpy(tab2, tmp.c_str());

注意缓冲区溢出。

最简单的方法就是这样

std::string myWord = "myWord";
char myArray[myWord.size()+1];//as 1 char space for null is also required
strcpy(myArray, myWord.c_str());
str.copy(cstr, str.length()+1); // since C++11
cstr[str.copy(cstr, str.length())] = '\0';  // before C++11
cstr[str.copy(cstr, sizeof(cstr)-1)] = '\0';  // before C++11 (safe)

在 C + + 中避免使用 C 语言是更好的做法,因此应该选择 : copy而不是 严格

好吧,我很震惊没有人真正给出一个好的答案,现在轮到我了

  1. 常量字符数组常量字符数组对你来说已经足够好了,所以你可以选择,

    const char *array = tmp.c_str();
    
  2. Or you need to modify the char array so constant is not ok, then just go with this

    char *array = &tmp[0];
    

Both of them are just assignment operations and most of the time that is just what you need, if you really need a new copy then follow other fellows answers.

如果事先不知道字符串的大小,可以动态分配一个数组:

auto tab2 = std::make_unique<char[]>(temp.size() + 1);
std::strcpy(tab2.get(), temp.c_str());

试试这样,应该能行。

string line="hello world";
char * data = new char[line.size() + 1];
copy(line.begin(), line.end(), data);
data[line.size()] = '\0';

好吧,我知道这可能相当愚蠢的 和简单,但我认为它应该工作:

string n;
cin>> n;
char b[200];
for (int i = 0; i < sizeof(n); i++)
{
b[i] = n[i];
cout<< b[i]<< " ";
}

如果你正在使用 C + + 11或更高版本,我建议使用 std::snprintf而不是 std::strcpystd::strncpy,因为它的安全性(即,你决定有多少个字符可以写入你的缓冲区) ,并且因为它为你终止了字符串(所以你不必担心它)。事情是这样的:

#include <string>
#include <cstdio>


std::string tmp = "cat";
char tab2[1024];
std::snprintf(tab2, sizeof(tab2), "%s", tmp.c_str());

在 C + + 17中,你可以这样选择:

#include <string>
#include <cstdio>
#include <iterator>


std::string tmp = "cat";
char tab2[1024];
std::snprintf(tab2, std::size(tab2), "%s", tmp.c_str());