strcat连接a和b而不实际更改a或b

时间:2015-04-05 19:51:55

标签: c string concatenation strcpy strcat

我知道我可以这样声明

    strcat( a, b );
    int alen = strlen( a );
    printf("a and b concatenated = %s and its length is %d\n", a, alen );

但是,我想保留一个,所以我尝试使用更像这样的东西:

    strcat( a, b );
    int xlen = strlen( x );
    printf("a and b concatenated = %s and its length is %d\n", x, xlen );

如何使用strcat修复第一行,以便将a和b连接成x?

2 个答案:

答案 0 :(得分:4)

您应该使用以下内容: -

strcpy(x,a);
strcat(x,b);
int xlen = strlen(x);
printf("a and b concatenated = %s and its length is %d\n", x, xlen );

Voila,那就是它。

答案 1 :(得分:0)

我发现以下内容也适用:

    /* Concatenate a and b */
    char x[SIZE1+SIZE2] = “”;
    strcat(x , a );
    strcat(x , b );

    printf("a and b concatenated = %s and its length is %d\n", x, (int)strlen(x) );