c - 如何编写 C 字符串函数 : strncpy , strncat 和 strncmp

标签 c string function

我正在解决这个 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/

相关文章:

c - 一核专用单进程

c - 链表程序错误

c - C中的多线程客户端-服务器套接字编程

C 程序显示最多输入的 %2==0 个数字,直到您输入数字 %2!=0 && %7==0

javascript - 使用 jQuery 查找文本并替换所有匹配的内容

c++ - 来自 std::unordered_set<char> 的有效构造 std::string

java - 比较两个字符串并按字母顺序对它们进行排序

java - 通用函数stream.map

javascript - 函数级作用域和 block 级作用域的区别

java - 选择 Java 函数调用中的按值传递行为