一直觉得自己眼高手低, 平时也懒得写代码, 下定决心要克服这个毛病,于是开始了重新拿起 the c programming languages 这本C语言圣经做做上面的练习题.就当是练手吧.
这次从字符串操作部分入手,实现自己的库,争取多写,多思考.而后看看一下coreutilities的GNU和NetBSD实现,接着看看(e)glibc,再以后,再打算吧.希望能有高手指出自己的不足,提高自己,一切以学习为目的.
/*
* =====================================================================
*
* Filename: wolf_string.c
*
* Description: Defination for my str lib
*
* Version: 1.0
* Created: 2011年09月01日 13时14分35秒
* Revision: none
* Compiler: gcc
*
* Author: wolfpython(walter) (), wolfpythonlondon@gmail.com
* Company:
*
* ====================================================================
*/
#include "wolf_string.h"
#include <assert.h>
int
wolf_strlen(char *src)
{
int i = 0;
while(*src != '\0') {
src++;
i++;
}
return i;
}
int
wolf_strlen_1(char *src)
{
char *p = src;
while(*src != '\0')
src++;
return src-p;
}
void
wolf_strcpy(char *des, char *src)
{
/* if des is a null pointer, its not safe to modify the mem
* if the src is a null pointer, it doesnt make any sense
* */
assert(des != NULL && src != NULL);
while((*des = *src) != '\0') {
des++;
src++;
}
}
void
wolf_strcpy_1(char *des, char *src)
{
/* if des is a null pointer, its not safe to modify the mem
* if the src is a null pointer, it doesnt make any sense
* */
assert(des != NULL && src != NULL);
while(*des++ = *src++)
;
}
int
wolf_strcmp(char *des, char *src)
{
/* if des is a null pointer, its not safe to modify the mem
* if the src is a null pointer, it doesnt make any sense
* */
assert(des != NULL && src != NULL);
while(*des == *src) {
if(*des == '\0') {
return 0;
}
des++;
src++;
}
return *des - *src;
}
void
wolf_strcat(char *des, char *src)
{
/* it doesnt matter if the src is a null pointer */
assert(des != NULL);
while(*des != '\0')
des++;
while(*des++ = *src++)
;
}
/*
*if t is at the end of s, return 1,
*else return 0
* */
int
wolf_strend(char *s, char *t)
{
int tsize;
char *thead = t; // the head of t
/* it doesnt make any sense if t is a null pointer */
assert(t != NULL);
if( s == NULL) return 0;
while(*s != '\0')
s++;
while(*t != '\0')
t++;
tsize = t - thead;
while(tsize-- > 0) {
if(*s != *t)
return 0;
s--;
t--;
}
return 1;
}