[C语言]字符串连接(追加)strcat函数

  • Post author:
  • Post category:其他



连接字符串

将源字符串的副本追加到目标字符串。目标中的终止空字符被源的第一个字符覆盖,并且在目标中由两者串联形成的新字符串的末尾包含一个空字符。

目的地和来源不得重叠。


参数


目的地

指向目标数组的指针,该数组应包含 C 字符串,并且足够大以包含串联的结果字符串。



要追加的 C 字符串。这不应与目标重叠。


返回值

返回目标。

例:

#include <stdio.h>
int main() {
    char arr1[20] = "hello ";//追加world!
    char arr2[] = "world!";
    strcat(arr1, arr2);//字符串追加(连接)
    printf("%s\n", arr1);
    return 0;
}

运行结果:

实现strcat

#include <stdio.h>
#include <assert.h>
char* my_strcat(char* destination,const char* source) {
    assert(destination);
    assert(source);
    char* start = destination;
    //1.找目标字符串中的\0
    while (*start) {
        start++;
    }
    //2.追加源字符串
    while (*start++ = *source++) {
        ;
    }
    return destination;
}
int main() {
    char arr1[20] = "hello ";//追加world!
    char arr2[] = "world!";
    my_strcat(arr1, arr2);
    printf("%s\n", arr1);
    return 0;
}

运行结果:



版权声明:本文为qq_43559301原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。