Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert char array to string use C

Tags:

arrays

c

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]
like image 230
ARTAS Avatar asked Jan 15 '13 18:01

ARTAS


People also ask

How do I convert an array to a string?

toString() method: Arrays. toString() method is used to return a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the characters “, ” (a comma followed by a space).

How do you convert char to string?

We can convert a char to a string object in java by using the Character. toString() method.

How does ToCharArray work in C#?

In C#, ToCharArray() is a string method. This method is used to copy the characters from a specified string in the current instance to a Unicode character array or the characters of a specified substring in the current instance to a Unicode character array.

How do you convert ToCharArray to string?

char[] arr = { 'p', 'q', 'r', 's' }; The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);


2 Answers

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'; 
like image 146
Mike Avatar answered Sep 24 '22 18:09

Mike


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

char * strncpy(char * destination, const char * source, size_t num);

like so:

strncpy(string, array, 20);
string[20] = '\0'

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

like image 32
Alex DiCarlo Avatar answered Sep 22 '22 18:09

Alex DiCarlo