公司笔试和面试中常要你编写strcpy/strcmp/memcpy/memcmp/strstr/atoi 等等这样的基础函数的实现。
我想在这儿总结下:(如下代码都是来自最新Linux kernel的库函数)
---------------------------------------------------------------------------------------
-
//strcpy in linux kernel linux-3.3/linux/lib/string.c
-
char *strcpy(char *dest, const char *src) {
-
char *tmp = dest; //很多时候可以在这儿对传入参数进行有效检查。内核里面没有这样做。
-
while ((*dest++ = *src++) != '\0')
-
/* nothing */;
-
return tmp;
-
}
-----------------------------------------------------------------------------------------
-
int strcmp(const char *cs, const char *ct)
-
{
-
unsigned char c1, c2;
-
-
while (1) {
-
c1 = *cs++;
-
c2 = *ct++;
-
if (c1 != c2)
-
return c1 < c2 ? -1 : 1;
-
if (!c1)
-
break;
-
}
-
return 0;
-
}
------------------------------------------------------------------------------------------------
-
void *memcpy(void *dest, const void *src, size_t count)
-
{
-
char *tmp = dest;
-
const char *s = src;
-
-
while (count--)
-
*tmp++ = *s++;
-
return dest;
-
}
-----------------------------------------------------------------------------------------------
-
int memcmp(const void *cs, const void *ct, size_t count) {
-
const unsigned char *su1, *su2;
-
int res = 0;
-
-
for (su1 = cs, su2 = ct; 0 < count; ++su1, ++su2, count--)
-
if ((res = *su1 - *su2) != 0)
-
break;
-
return res;
-
}
-----------------------------------------------------------------------------------------------
-
char *strstr(const char *s1, const char *s2)
-
{
-
size_t l1, l2;
-
-
l2 = strlen(s2);
-
if (!l2)
-
return (char *)s1;
-
l1 = strlen(s1);
-
while (l1 >= l2) {
-
l1--;
-
if (!memcmp(s1, s2, l2))
-
return (char *)s1;
-
s1++;
-
}
-
return NULL;
-
}
-----------------------------------------------------------------------------------------------
阅读(1085) | 评论(0) | 转发(0) |