How do I concatenate two strings in C?

后端 未结 11 1140
春和景丽
春和景丽 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 <stdlib.h>
    #include <string.h>
    
    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.

    0 讨论(0)
  • 2020-11-22 16:40

    Without GNU extension:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(void) {
        const char str1[] = "First";
        const char str2[] = "Second";
        char *res;
    
        res = malloc(strlen(str1) + strlen(str2) + 1);
        if (!res) {
            fprintf(stderr, "malloc() failed: insufficient memory!\n");
            return EXIT_FAILURE;
        }
    
        strcpy(res, str1);
        strcat(res, str2);
    
        printf("Result: '%s'\n", res);
        free(res);
        return EXIT_SUCCESS;
    }
    

    Alternatively with GNU extension:

    #define _GNU_SOURCE
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(void) {
        const char str1[] = "First";
        const char str2[] = "Second";
        char *res;
    
        if (-1 == asprintf(&res, "%s%s", str1, str2)) {
            fprintf(stderr, "asprintf() failed: insufficient memory!\n");
            return EXIT_FAILURE;
        }
    
        printf("Result: '%s'\n", res);
        free(res);
        return EXIT_SUCCESS;
    }
    

    See malloc, free and asprintf for more details.

    0 讨论(0)
  • 2020-11-22 16:40

    Concatenate Strings

    Concatenating any two strings in C can be done in atleast 3 ways :-

    1) By copying string 2 to the end of string 1

    #include <stdio.h>
    #include <string.h>
    #define MAX 100
    int main()
    {
      char str1[MAX],str2[MAX];
      int i,j=0;
      printf("Input string 1: ");
      gets(str1);
      printf("\nInput string 2: ");
      gets(str2);
      for(i=strlen(str1);str2[j]!='\0';i++)  //Copying string 2 to the end of string 1
      {
         str1[i]=str2[j];
         j++;
      }
      str1[i]='\0';
      printf("\nConcatenated string: ");
      puts(str1);
      return 0;
    }
    

    2) By copying string 1 and string 2 to string 3

    #include <stdio.h>
    #include <string.h>
    #define MAX 100
    int main()
    {
      char str1[MAX],str2[MAX],str3[MAX];
      int i,j=0,count=0;
      printf("Input string 1: ");
      gets(str1);
      printf("\nInput string 2: ");
      gets(str2);
      for(i=0;str1[i]!='\0';i++)          //Copying string 1 to string 3
      {
        str3[i]=str1[i];
        count++;
      }
      for(i=count;str2[j]!='\0';i++)     //Copying string 2 to the end of string 3
      {
        str3[i]=str2[j];
        j++;
      }
      str3[i]='\0';
      printf("\nConcatenated string : ");
      puts(str3);
      return 0;
    }
    

    3) By using strcat() function

    #include <stdio.h>
    #include <string.h>
    #define MAX 100
    int main()
    {
      char str1[MAX],str2[MAX];
      printf("Input string 1: ");
      gets(str1);
      printf("\nInput string 2: ");
      gets(str2);
      strcat(str1,str2);                    //strcat() function
      printf("\nConcatenated string : ");
      puts(str1);
      return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 16:46
    #include <stdio.h>
    
    int main(){
        char name[] =  "derp" "herp";
        printf("\"%s\"\n", name);//"derpherp"
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 16:50

    I'll assume you need it for one-off things. I'll assume you're a PC developer.

    Use the Stack, Luke. Use it everywhere. Don't use malloc / free for small allocations, ever.

    #include <string.h>
    #include <stdio.h>
    
    #define STR_SIZE 10000
    
    int main()
    {
      char s1[] = "oppa";
      char s2[] = "gangnam";
      char s3[] = "style";
    
      {
        char result[STR_SIZE] = {0};
        snprintf(result, sizeof(result), "%s %s %s", s1, s2, s3);
        printf("%s\n", result);
      }
    }
    

    If 10 KB per string won't be enough, add a zero to the size and don't bother, - they'll release their stack memory at the end of the scopes anyway.

    0 讨论(0)
  • 2020-11-22 16:51

    David Heffernan explained the issue in his answer, and I wrote the improved code. See below.

    A generic function

    We can write a useful variadic function to concatenate any number of strings:

    #include <stdlib.h>       // calloc
    #include <stdarg.h>       // va_*
    #include <string.h>       // strlen, strcpy
    
    char* concat(int count, ...)
    {
        va_list ap;
        int i;
    
        // Find required length to store merged string
        int len = 1; // room for NULL
        va_start(ap, count);
        for(i=0 ; i<count ; i++)
            len += strlen(va_arg(ap, char*));
        va_end(ap);
    
        // Allocate memory to concat strings
        char *merged = calloc(sizeof(char),len);
        int null_pos = 0;
    
        // Actually concatenate strings
        va_start(ap, count);
        for(i=0 ; i<count ; i++)
        {
            char *s = va_arg(ap, char*);
            strcpy(merged+null_pos, s);
            null_pos += strlen(s);
        }
        va_end(ap);
    
        return merged;
    }
    

    Usage

    #include <stdio.h>        // printf
    
    void println(char *line)
    {
        printf("%s\n", line);
    }
    
    int main(int argc, char* argv[])
    {
        char *str;
    
        str = concat(0);             println(str); free(str);
        str = concat(1,"a");         println(str); free(str);
        str = concat(2,"a","b");     println(str); free(str);
        str = concat(3,"a","b","c"); println(str); free(str);
    
        return 0;
    }
    

    Output:

      // Empty line
    a
    ab
    abc
    

    Clean-up

    Note that you should free up the allocated memory when it becomes unneeded to avoid memory leaks:

    char *str = concat(2,"a","b");
    println(str);
    free(str);
    
    0 讨论(0)
提交回复
热议问题