How do I concatenate const/literal strings in C?

前端 未结 17 1504
醉梦人生
醉梦人生 2020-11-21 23:45

I\'m working in C, and I have to concatenate a few things.

Right now I have this:

message = strcat(\"TEXT \", var);

message2 = strcat(strcat(\"TEXT          


        
17条回答
  •  别跟我提以往
    2020-11-22 00:27

    As people pointed out string handling improved much. So you may want to learn how to use the C++ string library instead of C-style strings. However here is a solution in pure C

    #include 
    #include 
    #include 
    
    void appendToHello(const char *s) {
        const char *const hello = "hello ";
    
        const size_t sLength     = strlen(s);
        const size_t helloLength = strlen(hello);
        const size_t totalLength = sLength + helloLength;
    
        char *const strBuf = malloc(totalLength + 1);
        if (strBuf == NULL) {
            fprintf(stderr, "malloc failed\n");
            exit(EXIT_FAILURE);
        }
    
        strcpy(strBuf, hello);
        strcpy(strBuf + helloLength, s);
    
        puts(strBuf);
    
        free(strBuf);
    
    }
    
    int main (void) {
        appendToHello("blah blah");
        return 0;
    }
    

    I am not sure whether it is correct/safe but right now I could not find a better way to do this in ANSI C.

提交回复
热议问题