Append Char To String in C?

前端 未结 9 1105
滥情空心
滥情空心 2020-11-27 16:17

How do I append a single char to a string in C?

i.e

char* str = \"blablabla\";
char c = \'H\';
str_append(str,c); /* blablablaH */
9条回答
  •  攒了一身酷
    2020-11-27 16:34

    To append a char to a string in C, you first have to ensure that the memory buffer containing the string is large enough to accomodate an extra character. In your example program, you'd have to allocate a new, additional, memory block because the given literal string cannot be modified.

    Here's a sample:

    #include 
    
    int main()
    {
        char *str = "blablabla";
        char c = 'H';
    
        size_t len = strlen(str);
        char *str2 = malloc(len + 1 + 1 ); /* one for extra char, one for trailing zero */
        strcpy(str2, str);
        str2[len] = c;
        str2[len + 1] = '\0';
    
        printf( "%s\n", str2 ); /* prints "blablablaH" */
    
        free( str2 );
    }
    

    First, use malloc to allocate a new chunk of memory which is large enough to accomodate all characters of the input string, the extra char to append - and the final zero. Then call strcpy to copy the input string into the new buffer. Finally, change the last two bytes in the new buffer to tack on the character to add as well as the trailing zero.

提交回复
热议问题