字符串操作函数实现

一直觉得自己眼高手低, 平时也懒得写代码, 下定决心要克服这个毛病,于是开始了重新拿起 the c programming languages 这本C语言圣经做做上面的练习题.就当是练手吧.


这次从字符串操作部分入手,实现自己的库,争取多写,多思考.而后看看一下coreutilitiesGNUNetBSD实现,接着看看(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;
}








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值