1.库函数

库函数

  • 1.内存初始化
  • 2.内存拷贝
  • 3.内存比较
  • 4.求字符串长度
  • 5.字符串拷贝
  • 6.字符串比较
  • 7.字符串连接
  • 8.查找字符串中的一个字符,并返回第一个字符的地址

1.内存初始化

void* const mymemset(void* const pData, int val, size_t numofbytes)
{
	//让无指针类型学习
	unsigned char* const _pData = (unsigned char* const)pData;
	for (size_t i = 0; i < numofbytes; ++i)
	{
		_pData[i] = val;
	}
	return pData;
}

2.内存拷贝

void* const mymemcpy(void* const pDest, void const* const pSrc, size_t numofbytes)
{
	if (pDest != pSrc)
	{
		//让无指针类型学习
		unsigned char* const p1 = (unsigned char* const)pDest;
		unsigned char const* const p2 = (unsigned char const* const)pSrc;
		if (p1 < p2)
		{
			for (size_t i = 0; i < numofbytes; ++i)
			{
				p1[i] = p2[i];
			}
		}
		else {
			for (int i = numofbytes - 1; i >= 0; --i)
			{
				p1[i] = p2[i];
			}
		}
	}
	return pDest;
}

3.内存比较

int mymemcmp(void const* const pBuff1, void const* const pBuff2, size_t numofbytes)
{
	if (pBuff1 != pBuff2)
	{
		unsigned char const* const p1 = (unsigned char const* const)pBuff1;
		unsigned char const* const p2 = (unsigned char const* const)pBuff2;
		for (size_t i = 0; i < numofbytes; ++i)
		{
			if (p1[i] > p2[i])
			{
				return 1;
			}
			if (p1[i] < p2[i])
			{
				return -1;
			}
		}
	}
	return 0;
}

4.求字符串长度

size_t mystrlen(char const* const pstr)
{
	int index = 0;
	while (pstr[index] != '\0')
	{
		++index;
	}
	return index;
}

5.字符串拷贝

char* const mystrcpy(char* const pDest, char const* const pSrc)
{
	if (pDest != pSrc)
	{
		if (pDest < pSrc)
		{
			int index = 0;
			while (pDest[index] = pSrc[index])
			{
				++index;
			}
		}
		else {
			int srclen = mystrlen(pSrc);
			//从'\0'开始拷贝
			for (int i = srclen; i >= 0; --i)
			{
				pDest[i] = pSrc[i];
			}
		}
	}
	return pDest;
}

6.字符串比较

int mystrcmp(char const* const pstr1, char const* const pstr2)
{
	if (pstr1 != pstr2)
	{
		int index = 0;
		while (pstr1[index] != '\0' || pstr2[index] != '\0')
		{
			if (pstr1[index] > pstr2[index])
			{
				return 1;
			}
			if (pstr1[index] < pstr2[index])
			{
				return -1;
			}
			++index;
		}
	}
	return 0;
}

7.字符串连接

char* const mystrcat(char* const pDest, char const* const pSrc)
{
	char* const _pDest = pDest + mystrlen(pDest);
	if (_pDest < pSrc)
	{
		int index = 0;
		while (_pDest[index] = pSrc[index])
		{
			++index;
		}
	}
	else {
		int srclen = mystrlen(pSrc);
		for (int i = srclen; i >= 0; --i)
		{
			_pDest[i] = pSrc[i];
		}
	}
	return pDest;
}

8.查找字符串中的一个字符,并返回第一个字符的地址

char* const mystrchr(char const* const pstr, int key)
{
	int index = 0;
	while (pstr[index]!='\0')
	{
		if (pstr[index] == key)
		{
			return (char* const)(pstr + index);
		}
		++index;
	}
	return nullptr;
}

你可能感兴趣的:(数据结构,算法)