srtcpy
原型声明:extern char *strcpy(char* dest, const char *src);
头文件:#include <string.h> 和 #include <stdio.h>
功能:把从src地址开始且含有\0结束符的字符串复制到以dest开始的地址空间
说明:src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。
原型声明:extern char *strcpy(char* dest, const char *src);
头文件:#include <string.h> 和 #include <stdio.h>
功能:把从src地址开始且含有\0结束符的字符串复制到以dest开始的地址空间
说明:src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。
返回指向dest的指针。
代码1:
#include <stdio.h>
#include <string.h>
//字符串的复制
void Mystrcpy (char *str1, char *str2)
{
char *p = str1; //指向字符串1的首字符
while (*str2)
{
*(p++) = *(str2++); //复制字符串2
}
*p = '\0';
puts (str1);
}
int main ()
{
char str1[100] = "hello";
char str2[10] = "world***";
Mystrcpy (str1, str2);
return 0
代码2:
#include <stdio.h>
#include <string.h>
void Mystrncpy (char *str1, char *str2, int n)
{
char *p = str1;
int index = 0; //记录已复制的长度
if (n > strlen(str2)) //复制的长度不能大于字符串自身长度
return;
while (index < n)
{
*(p++) = *(str2++);
index++;
}
puts (str1);
}
int main()
{
char str1[100] = "Hello";
char str2[] = "World";
int n;
scanf ("%d",&n); //输入要复制的长度
Mystrncpy (str1, str2, n);
return 0;
}