strcpy函数详解
strcpy函数原型
char *strcpy( char *strDestination, const char *strSource);
库函数下的strcpy
#include<stdio.h>
#include<string.h>
int main()
{
char arr1[20] = { 0 };
char arr2[] = "abcdef";
strcpy(arr1, arr2);
printf("%s", arr1);
return 0;
}
模拟实现strcpy函数
#include<stdio.h>
void my_strcpy(char* dest, char* source)
{
while (*source != '\0')
{
*dest = *source;
dest++;
source++;
}
*dest = *source;
}
int main()
{
char arr1[20] = { 0 };
char arr2[] = "hello word";
my_strcpy(arr1, arr2);
printf("%s", arr1);
return 0;
}
#include<stdio.h>
#include<assert.h>
char* my_strcpy(char* dest, const char* source)
{
assert(dest);
assert(source);
char* ret = dest;
while(*dest++=*source++)
{
;
}
return ret;
}
int main()
{
char arr1[20] = { 0 };
char arr2[] = "abcdef";
my_strcpy(arr1, arr2);
printf("%s", arr1);
return 0;
}
strcpy函数的注意事项
- 源字符串必须以\0作为结束
- strcpy会将源字符串中的\0拷贝到目标空间中
- 目标空间必须要足够大,以确保存放源字符串
- 目标空间必须可变
- strcpy函数的模拟实现
strncpy的函数原型
char *strncpy( char *strDest, const char *strSource, size_t count );
strncpy的注意事项
- 拷贝count个字符从源到目标空间
- 如果源字符串的长度小于count,则拷贝完源字符串之后,在目标的后面追加0(也就是\0),编译器会主动去追加\0
模拟实现strncpy
#include<stdio.h>
#include<assert.h>
#include<string.h>
char* my_strncpy(char* dest, const char* src, size_t count)
{
assert(dest);
assert(src);
char* res = dest;
int sz = 0;
if (strlen(src) < count)
{
sz = count - strlen(src);
count = strlen(src);
}
while (count--)
{
*dest++ = *src++;
}
while (sz--)
{
*dest++ = '\0';
}
return res;
}
int main()
{
char arr1[] = "hello world";
char arr2[] = "nihaoa";
my_strncpy(arr1, arr2, 8);
printf("%s", arr1);
return 0;
}