面试中常考的C函数库中的字符串处理函数

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#include<assert.h>





int myStrlen(const char *strDest)

{

	assert(NULL != strDest);

	const char *p = strDest;

	int len = 0;

	while( (*p) != '\0' )

	{

		len++;

		p++;

	}

	return len;

}



int itrStrlen(const char *strDest)

{

	assert(NULL != strDest);

	return ('\0' != *strDest) ? (1 + itrStrlen(strDest+1)) : 0;

}



char* myStrcpy(char *strDst, const char *strSrc)

{

	assert(NULL != strDst && NULL != strSrc);

	char *strRst = strDst;

	while( *strSrc != '\0' )

		*(strDst++) = *(strSrc++);

	return strRst;

}



int myStrcmp(const char *strL, const char *strR)

{

	assert(NULL != strL && NULL != strR);

	int ret = 0;

	const char *left = strL;

	const char *right = strR;

	while( (!(ret = (*left - *right))) && (*right != '\0') )

	{

		left++;

		right++;

	}

	if(ret < 0) ret = -1;

	else if(ret > 0) ret = 1;

	return ret;

}

//???上网查

void * myMemset(void *buffer, int c, size_t count)

{

	assert(NULL != buffer);

	char *p = (char *)buffer;

	while(count--)

	{

		*p = 'c'; 

		printf("%d", *p);

		p++;

	}

	return buffer;

}



char * myStrchr(char *str, int c)

{

	assert(NULL != str);

	for(; *str != (char)c; str++);

	if(*str == '\0') return NULL;

	return str;

}



char * myStrcat(char *strDes, const char *strSrc)

{

	assert(NULL != strDes && NULL != strSrc);

	char *addr = strDes;

	while(*strDes != '\0') strDes++;

	while( (*strDes++ = *strSrc++) != '\0' );

	return addr;

}

//*有点难度

void * myMemcpy(void *to, const void *from, size_t count)

{

	assert(NULL != to && NULL != from);

	void *ret = to;

	char *pto = (char *)to;

	char *pfrom = (char *)from;

	assert(pto < pfrom || pto > (pfrom+count-1));//!!!

	while(count--)

	{

		*pto++ = *pfrom++;

	}

	return ret;

}



void test()

{

	//test strlen

	char *s = "dfdafdaf";

	int len = myStrlen(s);

	char *ss = "";

	len = myStrlen(ss);

	printf("%d\n", len);



	//test strcpy

	char *str = (char *)malloc(sizeof(char)*10);

	strcpy(str, s);

	//strcpy(str, "abcdefg");

	//strcpy(ss, s); //由于未对ss分配内存,因此会出现异常

	printf("%s\n", str);



	//test strcmp

	int ret = myStrcmp(str, s);

	printf("%d\n", ret);

	ret = myStrcmp(str, ss);

	printf("%d\n", ret);

	ret = myStrcmp(str, "zfdfd");

	printf("%d\n", ret);



	//test memset

	int a[10];

	myMemset(a, 1, sizeof(int)*10);



	//test strchr

	char *p = myStrchr(s, 'a');

	printf("\n%c\n", *p);



	//test strcat

	//char *cat = (char *)malloc(sizeof(char)*20);

	myStrcat(str, "aab");

	printf("%s\n", str);





}





int main()

{

	test();

	return 0;

}


你可能感兴趣的:(字符串处理)