How do I concatenate two strings in C?

后端 未结 11 1206
春和景丽
春和景丽 2020-11-22 16:00

How do I add two strings?

I tried name = \"derp\" + \"herp\";, but I got an error:

Expression must have integral or enum type

11条回答
  •  我在风中等你
    2020-11-22 16:40

    C does not have the support for strings that some other languages have. A string in C is just a pointer to an array of char that is terminated by the first null character. There is no string concatenation operator in C.

    Use strcat to concatenate two strings. You could use the following function to do it:

    #include 
    #include 
    
    char* concat(const char *s1, const char *s2)
    {
        char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
        // in real code you would check for errors in malloc here
        strcpy(result, s1);
        strcat(result, s2);
        return result;
    }
    

    This is not the fastest way to do this, but you shouldn't be worrying about that now. Note that the function returns a block of heap allocated memory to the caller and passes on ownership of that memory. It is the responsibility of the caller to free the memory when it is no longer needed.

    Call the function like this:

    char* s = concat("derp", "herp");
    // do things with s
    free(s); // deallocate the string
    

    If you did happen to be bothered by performance then you would want to avoid repeatedly scanning the input buffers looking for the null-terminator.

    char* concat(const char *s1, const char *s2)
    {
        const size_t len1 = strlen(s1);
        const size_t len2 = strlen(s2);
        char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
        // in real code you would check for errors in malloc here
        memcpy(result, s1, len1);
        memcpy(result + len1, s2, len2 + 1); // +1 to copy the null-terminator
        return result;
    }
    

    If you are planning to do a lot of work with strings then you may be better off using a different language that has first class support for strings.

提交回复
热议问题