《C程序设计语言》5-5
题目:实现库函数strncpy strncat strncmp,它们最多对参数字符串中的前N个字符进行操作。例如:函数strncpy(s, t, n) 将t中最多前n个字符复制到s中。
#include <stdio.h>
/*对字符串中的前n个字符进行操作*/
void strncpy(char *, char *, int);
void strncat(char *, char *, int);
int strncmp(char *, char *, int);
int main()
{
char s[] = "ajy";
char t[] = "beautiful";
char *p = s;
int n = 3;
strncpy(p, t, n);
printf("%s\n", s);
strncat(s, t, n);
printf("%s\n", s);
int flag = strncmp(s, t, n);
if(flag < 0)
printf("%s < %s\n", s, t);
else if(flag == 0)
printf("%s = %s\n", s, t);
else
printf("%s > %s\n", s, t);
return 0;
}
//将t的前n个字符复制给s
void strncpy(char *s, char *t, int n)
{
int i;
for(i = 0; i < n; i++)
{
*s++ = *t++;
}
*s = '\0';
}
//将t的前n个字符添加到s的尾部
void strncat(char *s, char *t, int n)
{
while(*s++)
;
s--;
while(n--){
*s++ = *t++;
}
*s = '\0';
}
//将s的前n个字符与t进行比较
int strncmp(char *s, char *t, int n)
{
char *p = t + n;
for(; *s == *t && t < p; s++, t++){
if(*s == '\0' || *t == '\0')
break;
}
if(*s == *t)
return 0;
else
return *s - *t;
}
注意:将三个函数同时写在main函数里,都是对s进行操作,在第一个函数strncpy后,s已经发生变化,导致后面两个函数在使用此函数时,传递的是已经变化了的字符串。我想着在第一个函数前定义另一个指针指向s,但是由于s的内容发生变化,导致用新定义的指针p也是同样的情况。