我正在解决这个 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;
}
最佳答案
快速浏览似乎至少揭示了几个问题:
- 在 strncmp 中:对输入的 strlen() 调用无效。它们不必以空值终止。此外,返回值应为 <0、=0、>0,具体取决于相等性。
- strncpy:我相信库版本用\0 填充字符串到末尾。
关于c - 如何编写 C 字符串函数 : strncpy , strncat 和 strncmp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1996950/