转换字符数组字符串采用C [英] Convert char array to string use C

查看:119
本文介绍了转换字符数组字符串采用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个char数组转换为字符串。
事情是这样的:

 字符数组[20];
字符字符串[100];数组[0] ='1';
阵列[1] =7;
阵列[2] =8;
阵列[3] ='。';
阵列[4] ='9';
...

我想获得类似的东西:

 字符字符串[0] =数组//它被存放178.9 ....位置[0]


解决方案

你是说你有这样的:

 字符数组[20];字符字符串[100];
数组[0] ='1';
阵列[1] =7;
阵列[2] =8;
阵列[3] ='。';
阵列[4] ='9';

和你想有这样的:

 串[0] =178.9; //它被存储178.9 ....在位置[0]

您不能有。一个char拥有1个字符。而已。
A串在C是字符数组后跟一个标记字符(NULL结束符)。

现在,如果你想第一个X字符出阵列复制到字符串你可以做到这一点与的memcpy()

 的memcpy(字符串,数组,X);
字符串[X] ='\\ 0';

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]

解决方案

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).

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

memcpy(string, array, x);
string[x] = '\0'; 

这篇关于转换字符数组字符串采用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆