文章目录
一. 库函数strcpy()
参考文档:strcpy - C++ Reference (cplusplus.com)
char * strcpy ( char * destination, const char * source );
函数描述:拷贝字符串。
将source指向的C字符串复制到destination指向的数组中,包括结束的null字符(并在该点停止)。
为了避免溢出,destination指向的数组的大小应该足够长,以包含与source相同的C字符串(包括结束的null字符),并且不应该在内存中与source重叠。
函数参数:
- destination:指向要在其中复制内容的目标数组的指针。
- source:要复制的C字符串。
函数返回:目的内存的地址。
#include <stdio.h>
#include <assert.h>
#include <string.h>
int main()
{
const char* str = "hello strcpy()";
printf("%s\n", str); // hello strcpy()
char str_copy1[20] = {'\0'};
char* str_ret1 = strcpy(str_copy1, str);
printf("%s\n", str_copy1); // hello strcpy()
printf("%s\n", str_ret1); // hello strcpy()
return 0;
}
二. 库函数strncpy()
参考文档:strncpy - C++ Reference (cplusplus.com)
char * strncpy ( char * destination, const char * source, size_t num );
函数描述:从字符串中复制字符。
将源的第一个num字符复制到目标。如果在复制num个字符之前找到源C字符串的结尾(用空字符表示),则目的地将用零填充,直到向其写入总数为num个字符。
如果source大于num,则不会在destination的末尾隐式添加空字符。因此,在这种情况下,destination不应被视为以空结束的C字符串(这样读取会溢出)。
目的和源不应重叠(当重叠时,请参阅memmove以获得更安全的替代方案)。
函数描述:
- destination:指向要在其中复制内容的目标数组的指针。
- source:要复制的C字符串。
- num:要从源复制的最大字符数。Size_t是一个无符号整型。
函数返回:目的内存的地址。
#include <stdio.h>
#include <assert.h>
#include <string.h>
int main()
{
const char* str = "hello strcpy()";
printf("%s\n", str); // hello strcpy()
char str_copy1[20] = { '\0' };
char* str_ret1 = strncpy(str_copy1, str, 4);
printf("%s\n", str_copy1); // hell
printf("%s\n", str_ret1); // hell
}
三. 模拟strcpy()
#include <stdio.h>
#include <assert.h>
#include <string.h>
/// <summary>
/// 模拟strcpy()
/// </summary>
/// <param name="destination">拷贝目的地</param>
/// <param name="soure">拷贝源</param>
/// <returns>返回目的地</returns>
char* myStrcpy_1(char* destination, const char* soure)
{
assert(destination && soure);
// 指向第一个字符位置
char* pbegin = destination;
while (*destination++ = *soure++);
// 返回目的地
return pbegin;
}
/// <summary>
/// 模拟strcpy()
/// </summary>
/// <param name="destination">拷贝目的地</param>
/// <param name="soure">拷贝源</param>
/// <returns>返回目的地</returns>
char* myStrcpy_2(char* destination, const char* soure)
{
assert(destination && soure);
// 指向第一个字符位置
char* pbegin = destination;
while (*soure != '\0')
{
*destination = *soure;
destination++;
soure++;
}
// 返回目的地
return destination;
}
int main()
{
const char* str = "hello strcpy()";
printf("%s\n", str); // hello strcpy()
char str_copy1[20] = {'\0'};
char* str_ret1 = strcpy(str_copy1, str);
printf("%s\n", str_copy1); // hello strcpy()
printf("%s\n", str_ret1); // hello strcpy()
char str_copy2[20] = { '\0' };
char* str_ret2 = myStrcpy_1(str_copy2, str);
printf("%s\n", str_copy2); // hello strcpy()
printf("%s\n", str_ret2); // hello strcpy()
char str_copy3[20] = { '\0' };
char* str_ret3 = myStrcpy_2(str_copy3, str);
printf("%s\n", str_copy3); // hello strcpy()
printf("%s\n", str_ret3); // hello strcpy()
return 0;
}
打印结果: