1.strcat介绍
strcat --- 字符串追加
char * strcat ( char* destination, const char* source );
源头字符串与目的地字符串必须都以’\0‘结束;
目标空间必须足够大且可修改
2.如何使用
strcat的追加是从目的地字符串的‘\0’开始追加;追加时源头字符串的‘\0’会追加到目的地,而目的地的‘\0’被源头字符串的第一个字符所取代
错误示范:
char arr1[] = "hello" ; // arr1数组空间只有5个字节,将world追加过去 一共是10个字节
char arr2[] = "world" ;
造成了越界访问
char arr1[30] = "hello" ;
char arr2[] = "world" ; // 正确
strcat不能进行字符串的自我追加:strcat(arr1,arr1)// 错!
3.strcat的实现
#include<stdio.h>
#include<assert.h>
char* my_strcat(char* destination, const char* source)
{
char* ret = destination;
assert(destination && source);
//找到目的字符串的'\0'
while (*destination != '\0')
{
destination++;
}
//追加
while (*destination++ = *source++)
{
;
}
return ret;
}
int main()
{
char arr1[30] = "hello";
char arr2[] = "world";
my_strcat(arr1, arr2);
printf("%s\n", arr1);
return 0;
}