首页 > 试题广场 >

strncpy (sl,s2,n)函数从s2复制n个字符给s

[问答题]

strncpy (sl,s2,n)函数从s2复制n个字符给sl,并在必要时截断s2或为其填充额外的空字符。如果s2的长度等于或大于n,目标字符串就没有标志结束的空字符。函数返回sl。自己编写这个函数,并在一个使用循环语句为这个函数提供输入的完整程序中进行测试。

推荐
#include <stdio.h>
char *mystrncpy(char *p1, char *p2, int n);
int main(void)
{
 char str1[81];
 char str2[81];
 int n;
 do
 {
 puts("input string1:");
 gets(str1);
 puts("input string2:");
 gets(str2);
 puts("input the number of copying char:");
 scanf("%d",&n);
 getchar();
 puts("After copying:");
 puts(mystrncpy(str1, str2, n));
 puts("input any char except q to go on.");
 gets(str1);
 }
 while(*str1 != 'q');
 puts("Quit.");
 return 0;
}
char *mystrncpy(char *p1, char *p2, int n)
{
 char *p=p1;
 while(*p1++ != '\0') continue;
 *--p1 = *p2;
 n--;
 while(n>0 && *p2 != '\0')
 {
 *++p1 = *++p2;
 n--;
 }
 return p;
}

发表于 2018-05-05 21:52:05 回复(1)