Search code examples
cconcatenationstring-concatenation

C concatenate string variable string


I try to concatenate in the following form "string", variable, "string";

#include <stdio.h>

int main() {
        char *name = "Lannister";

        char write_letter[50] = "Here you are Mrs. ", name, " Welcome!\r\n"
                             "Getting Started\r\n"
                             "Interviews\r\n"
                             "Take-home Projects\r\n";
}

does anyone have idea how to do it?

I saw an example of sprintf(write_letter, "Here you are Mrs. %s Welcome!", name); but it is very difficult when i use large texts.


Solution

  • If the name is already decided at compile time and if there is no necessity to change the name during runtime then by all means choose the simplest alternative, i.e. -

    #define NAME "Lannister"
    
    char write_letter[] = "Here you are Mrs. " NAME " Welcome!\r\n"
                          "Getting Started\r\n"
                          "Interviews\r\n"
                          "Take-home Projects\r\n";
    

    Compile with highest warning level set. When you do that you will get a warning similar to "initializer-string for array of chars is too long" (this is the warning generated by GCC). 50 is too small for this array hence I have allowed the compiler to decide the array size (i.e. 'write_letter[]').

    If you need to change the string at runtime then use either strcat() -

    char write_letter[150] = "Here you are Mrs. ";
    char *name = "Lannister";
    char *write_letter_post = " Welcome!\r\n"
                              "Getting Started\r\n"
                              "Interviews\r\n"
                              "Take-home Projects\r\n";
    
    strcat(write_letter, name);
    strcat(write_letter, write_letter_post);
    /*Use strncat() to prevent buffer overflow possibilities.*/
    

    or, sprintf() -

    char *_write_letter = "Here you are Mrs. %s Welcome!\r\n"
                          "Getting Started\r\n"
                          "Interviews\r\n"
                          "Take-home Projects\r\n";
    char *name = "Lannister";
    char write_letter[150];
    
    sprintf(write_letter, _write_letter, name);
    /*Use snprintf() to prevent buffer overflow possibilities.*/