简体   繁体   中英

Concatenate two characters in c

How to concatenate two characters and store the result in a variable?

For example, I have 3 characters 'a' , 'b' and 'c' and I need to join them together and store them in an array and later use this array as a string:

#include <stdio.h>
#include <string.h>

char n[10];

main ()
{
    // now I want insert them in an array
    //ex: n = { a + b + c }
}

Simply:

char a = 'a', b = 'b', c = 'c';

char str[4];
str[0] = a;
str[1] = b;
str[2] = c;
str[3] = '\0';

Or, if you want str to be stored on the heap (eg if you plan on returning it from a function):

char *str = malloc(4);
str[0] = a;
...

Any introductory book on C should cover this.

An assignment similar to that can only be done when the char array is declared using array initialiation with a brace-enclosed list:

char a = 'a', b = 'b', c = 'c';
char n[10] = {a, b, c};

After the declaration you can't do it like this because a char array is not a modifiable lvalue :

n = {a, b, c}; //error

To insert characters in an array that has been previously initialized, you need to either insert them one by one as exemplified in another answer , or use some library function like sprintf .

sprintf(n, "%c%c%c", a, b, c);

In both of my examples the char array will be null terminated by the compiler so you can use it as a string, if you assign the characters one by one, make sure to place a null terminator at the end ( '\\0' ), only then will you have a propper string.

There are many ways, the following 2 methods have exactly the same results: (using your code as a starting point.)

#include <stdio.h>
#include <string.h>

int main(void)
{
    //Given the following
    char a = 'a';
    char b = 'b';
    char c = 'c';
    
    // assignment by initializer list at time of creation
    char n1[10] = {a,b,c};
    
    //usage of a string function
    char n2[10] = {0};   //initialize  array
    sprintf(n2, "%c%c%c", a, b, c);

    return 0;
}

Both result in a null terminated char arrays, or C strings .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM