【问题标题】:strcat to concatenate a and b without actually changing a or bstrcat 连接 a 和 b 而不实际更改 a 或 b
【发布时间】:2015-06-10 06:39:09
【问题描述】:

我知道我可以有这样的声明

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

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

    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 中?

【问题讨论】:

    标签: c string concatenation strcpy strcat


    【解决方案1】:

    您应该使用以下内容:-

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

    瞧,就是这样。

    【讨论】:

    • 谢谢,很简单。
    • 有一个重要的细节需要经常检查。具体来说,“x”的长度是否足以容纳 strlen(a) + strlen(b) +1
    【解决方案2】:

    我发现以下方法也可以:

        /* 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) );
    

    【讨论】:

    • 如果 SIZE1 和 SIZE2 与 strlen(a) 和 strlen(b) 相关,那么结果不够大,因为 strlen() 是尾随 NUL 字节的偏移量,所以需要加上 +1得到合适的长度。此外,第一行导致 x[0] 包含 '\0'。它不会清除所有 x[]。建议使用: ;char x[SIZE1+SIXE2+1] = {'\0'};清除整个数组并且不在只读内存中生成文字(仅包含一个 '\0' 字符)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2014-03-29
    • 1970-01-01
    • 2021-10-06
    • 2011-08-19
    • 1970-01-01
    相关资源
    最近更新 更多