c 语言字符串转数组,如何在C ++中将字符串转换为char数组?

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

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

#include

#include

#include

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(tmp.c_str());

cout << c << "\n";

//string to char

char tab2[1024];

// ?

return 0;

}

10个解决方案

100 votes

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

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());

Chowlett answered 2019-04-10T02:35:05Z

47 votes

好吧,我感到震惊的是,现在轮到我了,没有人真正给出了一个好的答案。 有两种情况;

一个常量字符数组对你来说足够好,所以你去,

char *array = &tmp[0];

或者您需要修改char数组,因此常量不正常,然后再使用它

char *array = &tmp[0];

它们都只是作业操作,大部分时间都是你需要的,如果你真的需要一个新的副本,那么请跟随其他研究员的答案。

rad answered 2019-04-10T02:36:19Z

15 votes

最简单的方法是做到这一点

std::string myWord = "myWord";

char myArray[myWord.size()+1];//as 1 char space for null is also required

strcpy(myArray, myWord.c_str());

Community answered 2019-04-10T02:36:46Z

9 votes

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是一种更好的做法,因此应该选择std :: string :: copy而不是strcpy。

Youka answered 2019-04-10T02:37:15Z

6 votes

只需将字符串复制到strcpy的数组中即可。

David Schwartz answered 2019-04-10T02:37:44Z

5 votes

尝试这种方式应该是有效的。

string line="hello world";

char * data = new char[line.size() + 1];

copy(line.begin(), line.end(), data);

data[line.size()] = '\0';

Tharindu Dhanushka answered 2019-04-10T02:38:15Z

4 votes

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

Marrow Gnawer answered 2019-04-10T02:38:43Z

2 votes

您可以使用strcpy(),如下所示:

strcpy(tab2, tmp.c_str());

注意缓冲区溢出。

Fred Larson answered 2019-04-10T02:39:32Z

1 votes

如果您事先不知道字符串的大小并且它可能变化很大,您可以获得一个动态分配的固定大小数组,其数组重载为strncpy:

auto tab2 = std::make_unique(temp.size() + 1);

std::strcpy(tab2.get(), temp.c_str());

请注意,此处不需要strncpy,因为数组首先被分配为足够大。

emlai answered 2019-04-10T02:40:12Z

0 votes

嗯,我知道这可能比简单而愚蠢,但我认为它应该有效:

string n;

cin>> n;

char b[200];

for (int i = 0; i < sizeof(n); i++)

{

b[i] = n[i];

cout<< b[i]<< " ";

}

SquircKle answered 2019-04-10T02:40:50Z

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值