Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate two char arrays?

If I have two char arrays like so:

char one[200];
char two[200];

And I then want to make a third which concatenates these how could I do it?

I have tried:

char three[400];
strcpy(three, one);
strcat(three, two);

But this doesn't seem to work. It does if one and two are setup like this:

char *one = "data";
char *two = "more data";

Anyone got any idea how to fix this?

Thanks

like image 411
ingh.am Avatar asked Jul 24 '10 11:07

ingh.am


People also ask

How do you concatenate a character array?

s = strcat( s1,...,sN ) horizontally concatenates the text in its input arguments. Each input argument can be a character array, a cell array of character vectors, or a string array. If any input is a string array, then the result is a string array.

How do you concatenate a char array in Java?

concat() method with Examples. The concat() method of Chars Class in the Guava library is used to concatenate the values of many arrays into a single array. These char arrays to be concatenated are specified as parameters to this method.

Can we use strcat on char array in C?

Also You can use strncat for one character addition. strcat requires a null-terminated string for its second argument.


1 Answers

If 'one' and 'two' does not contain a '\0' terminated string, then you can use this:

memcpy(tree, one, 200);
memcpy(&tree[200], two, 200);

This will copy all chars from both one and two disregarding string terminating char '\0'

like image 73
Martin Ingvar Kofoed Jensen Avatar answered Oct 10 '22 03:10

Martin Ingvar Kofoed Jensen