【发布时间】:2011-01-01 02:27:33
【问题描述】:
我正在解决这个 K&R 练习:
编写库函数 strncpy 、 strncat 和 strncmp 的版本,它们最多对其参数字符串的前 n 个字符进行操作。例如, strncpy(s,t,n) 最多将 t 的 n 个字符复制到 s 。完整的描述在附录 B 中。
所以我在徘徊,如果有一个包含这些字符串函数的源代码的网站,所以我可以检查我是否做错了什么。
这些是我写的版本:如果你能告诉我我是否在功能中有一些错误或者我应该添加/更正/改进的东西,我将不胜感激!
int strncmp(char *s, char *t, int n)
{
if(strlen(s) == strlen(t)) {
while(*s == *t && *s && n)
n--, s++, t++;
if(!n)
return 0; /* same length and same characters */
else
return 1; /* same length, doesnt has the same characters */
}
else
return strlen(s) - strlen(t);
}
char *strncpy(char *s, char *t, int n)
{
while(n-- && *s) {
*s = *t;
s++, t++;
}
if(strlen(t) < n)
*s = '\0';
return s;
}
char *strncat2(char *s, char *t, int n)
{
while(*s)
s++;
while(n-- && *t)
*s = *t, s++, t++;
*s = '\0';
return s;
}
【问题讨论】: