C语言 使用 C 将字符数组转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14344130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:03:05  来源:igfitidea点击:

Convert char array to string use C

carrays

提问by ARTAS

I need to convert a char array to string. Something like this:

我需要将字符数组转换为字符串。像这样的东西:

char array[20];
char string[100];

array[0]='1';
array[1]='7';
array[2]='8';
array[3]='.';
array[4]='9';
...

I would like to get something like that:

我想得到这样的东西:

char string[0]= array // where it was stored 178.9 ....in position [0]

回答by Mike

You're saying you have this:

你说你有这个:

char array[20]; char string[100];
array[0]='1'; 
array[1]='7'; 
array[2]='8'; 
array[3]='.'; 
array[4]='9';

And you'd like to have this:

你想要这个:

string[0]= "178.9"; // where it was stored 178.9 ....in position [0]

You can't have that. A char holds 1 character. That's it. A "string" in C is an array of characters followed by a sentinel character (NULL terminator).

你不能有那个。一个字符包含 1 个字符。就是这样。C 中的“字符串”是一个字符数组,后跟一个标记字符(NULL 终止符)。

Now if you want to copy the first x characters out of arrayto stringyou can do that with memcpy():

现在,如果你想第一个X字符复制出来arraystring你可以做到这一点memcpy()

memcpy(string, array, x);
string[x] = '
char * strncpy(char * destination, const char * source, size_t num);
';

回答by Alex DiCarlo

Assuming arrayis a character array that does not end in \0, you will want to use strncpy:

假设array是一个不以 结尾的字符数组\0,您将需要使用strncpy

strncpy(string, array, 20);
string[20] = '
char array[20]; char string[100];

array[0]='1'; array[1]='7'; array[2]='8'; array[3]='.'; array[4]='9'; array[5]='##代码##';
strcpy(string, array);
printf("%s\n", string);
'

like so:

像这样:

##代码##

Then stringwill be a null terminated C string, as desired.

然后string将是一个空终止的 C 字符串,根据需要。

回答by David Ranieri

You can use strcpybut remember to end the array with '\0'

您可以使用strcpy但请记住以'\0'

##代码##