Concatenating strings in C, which method is more efficient?

后端 未结 10 930
迷失自我
迷失自我 2020-11-28 19:51

I came across these two methods to concatenate strings:

Common part:

char* first= \"First\";
char* second = \"Second\";
char* both = malloc(strlen(fi         


        
10条回答
  •  再見小時候
    2020-11-28 20:50

    For readability, I'd go with

    char * s = malloc(snprintf(NULL, 0, "%s %s", first, second) + 1);
    sprintf(s, "%s %s", first, second);
    

    If your platform supports GNU extensions, you could also use asprintf():

    char * s = NULL;
    asprintf(&s, "%s %s", first, second);
    

    If you're stuck with the MS C Runtime, you have to use _scprintf() to determine the length of the resulting string:

    char * s = malloc(_scprintf("%s %s", first, second) + 1);
    sprintf(s, "%s %s", first, second);
    

    The following will most likely be the fastest solution:

    size_t len1 = strlen(first);
    size_t len2 = strlen(second);
    
    char * s = malloc(len1 + len2 + 2);
    memcpy(s, first, len1);
    s[len1] = ' ';
    memcpy(s + len1 + 1, second, len2 + 1); // includes terminating null
    

提交回复
热议问题