'How to combine three char to one
I had three char inside the array , which contain X1 X2 and X3
char array[3]={X1,X2,X3}
I want to combine three data which inside the array to one char
strcat(array[0]," ");
strcat(array[0],array[1]);
strcat(array[0]," ");
strcat(array[0],array[2]);
printf("%s",array[0])
I expect to get the result like this "X1 X2 X3"
Solution 1:[1]
I think you mean you want to concatenate 3 chars to a make one string.
Use sprintf with a sufficient array:
char str[6];
char array[3] = {'l', 'o', 'l'};
// write
sprintf(str, "%c %c %c", array[0], array[1], array[2]);
// print
printf(str);
Solution 2:[2]
you will need one more byte to have a null terminator.
char array[4] = { 'a', 'b', 'c', '\0' };
printf( "%s\n", array );
will give your abc
Solution 3:[3]
You can't do it that way. array is only 3 bytes long, so you can't have the string "a b c", which is 5+1 = 6 bytes long in it. And, of course, you can't call strcat(array[0], ... since array[0] is a single char, not a char *.
I'm not sure what you are looking for, but if you are given X1, X2 and X3 and want them in a string separated by spaces, you can do that :
void chars2str(char x1, char x2, char x3, char* dest) {
sprintf(dest, "%c %c %c", x1, x2, x3);
}
Of course, the dest argument must be big enough or something very nasty might happen.
char mystr[6];
char2str('a', 'b', 'c', mystr); /* Now mystr contains "a b c" */
Solution 4:[4]
The way you're using strcat is incorrect. array[0] is a char, which means it can hold only a single letter. It cannot hold X1 along with a " " or X2. Create another sufficiently big char array and then you can strcat to that.
Solution 5:[5]
#include <stdio.h>
char *join(char *result, const char array[], size_t size, const char sep){
size_t i,len=0;
for(i=0;i<size;++i){
len+=sprintf(result+len, "%c", array[i]);
if(i < size - 1)
len+=sprintf(result+len, "%c", sep);
}
return result;
}
int main(void){
const char array[] = { 'x', 'y', 'z'};
char result[6];
join(result, array, sizeof(array)/sizeof(char), ' ');
printf("%s", result);//"x y z"
return 0;
}
Solution 6:[6]
You could convert each individual char to a string, then concatenate them.
e.g.
char c = 'c';
char d = 'd';
string s1(1, c);
string s2(1, c);
string cd = s1 + s2;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Johan Lundberg |
| Solution 2 | Sudhee |
| Solution 3 | Fabien |
| Solution 4 | Varad |
| Solution 5 | |
| Solution 6 | Spencer Goff |
