How do I concatenate two strings in C?

后端 未结 11 1141
春和景丽
春和景丽 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:51

    You should use strcat, or better, strncat. Google it (the keyword is "concatenating").

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

    In C, you don't really have strings, as a generic first-class object. You have to manage them as arrays of characters, which mean that you have to determine how you would like to manage your arrays. One way is to normal variables, e.g. placed on the stack. Another way is to allocate them dynamically using malloc.

    Once you have that sorted, you can copy the content of one array to another, to concatenate two strings using strcpy or strcat.

    Having said that, C do have the concept of "string literals", which are strings known at compile time. When used, they will be a character array placed in read-only memory. It is, however, possible to concatenate two string literals by writing them next to each other, as in "foo" "bar", which will create the string literal "foobar".

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

    You cannot add string literals like that in C. You have to create a buffer of size of string literal one + string literal two + a byte for null termination character and copy the corresponding literals to that buffer and also make sure that it is null terminated. Or you can use library functions like strcat.

    0 讨论(0)
  • 2020-11-22 17:01
    #include <string.h>
    #include <stdio.h>
    int main()
    {
       int a,l;
       char str[50],str1[50],str3[100];
       printf("\nEnter a string: ");
       scanf("%s",str);
       str3[0]='\0';
       printf("\nEnter the string which you want to concat with string one: ");
       scanf("%s",str1);
       strcat(str3,str);
       strcat(str3,str1);
       printf("\nThe string is %s\n",str3);
    }
    
    0 讨论(0)
  • 2020-11-22 17:01

    using memcpy

    char *str1="hello";
    char *str2=" world";
    char *str3;
    
    str3=(char *) malloc (11 *sizeof(char));
    memcpy(str3,str1,5);
    memcpy(str3+strlen(str1),str2,6);
    
    printf("%s + %s = %s",str1,str2,str3);
    free(str3);
    
    0 讨论(0)
提交回复
热议问题