C语言str族函数strlen、strcpy、strcat、strcmp算法实现

1. 使用下标法实现strlen、strcpy、strcat、strcmp算法

1.1 strlen函数功能算法实现:

int StringLenght(char str[])
{
	int i = 0;
	while (str[i])
		++i;
	return i;
}

1.2 strcpy函数功能算法实现

void StringCopy(char strDestination[], const char strSource[])
{
	int i = -1;
	while (strDestination[++i] = strSource[i])
		;
}

1.3 strcat函数功能算法实现

void StringCat(char strDestination[], const char strSource[])
{
	int i = 0;
	while (strDestination[i])
		++i;
	int j = 0;
	while (strDestination[i++] = strSource[j++])
		;
}

1.4 strcmp函数功能算法实现

//如果strDestination > strSource返回大于零的数
//如果strDestination == strSource返回等于零的数
//如果strDestination < strSource返回小于零的数
int StringCmp(const char strDestination[], const char strSource[])
{
	//防止汉字和英文字母比较出现负数导致汉字小于英文字母
	unsigned char* pDes = (unsigned char*)strDestination;
	unsigned char* pSource = (unsigned char*)strSource;
	int i = 0;
	while (pDes[i] && pDes[i] == pSource[i])
		++i;
	return pDes[i] - pSource[i];
}

2. 使用指针法实现strlen、strcpy、strcat、strcmp算法

2.1 strlen函数功能算法实现:

int StringLenght(char* str)
{
	int i = 0;
	while (*str++)
		++i;
	return i;
}

2.2 strcpy函数功能算法实现

void StringCopy(char *strDestination, const char *strSource)
{
	while (*strDestination++ = *strSource++)
		;
}

2.3 strcat函数功能算法实现

void StringCat(char *strDestination, const char *strSource)
{
	while (*strDestination++)
		;
	*strDestination--;
	while (*strDestination++ = *strSource++;)
		;
}

2.4 strcmp函数功能算法实现

//如果strDestination > strSource返回大于零的数
//如果strDestination == strSource返回等于零的数
//如果strDestination < strSource返回小于零的数
int StringCmp(const char *strDestination, const char *strSource)
{
	//防止汉字和英文字母比较出现负数导致汉字小于英文字母
	unsigned char* pDes = (unsigned char*)strDestination;
	unsigned char* pSource = (unsigned char*)strSource;
	while (*pDes && *pDes == *pSource)
	{
		++pDes;
		++pSource;
	}
	return *pDes - *pSource;
}

3. 算法测试

#include <stdio.h>
int main(void)
{
	char s1[64];
	//将常量字符串"This is My"赋值给s1字符串数组
	StringCopy(s1, "This is My");
	puts(s1);
	//将常量字符串" CSDN Blog!"连接在给s1字符串后边
	StringCat(s1, " CSDN Blog!");
	puts(s1);
	//输出字符串s1的长度
	printf("len=%d\n", StringLenght(s1));

	char *str1 = "BC";
	char *str2 = "ABC";
	//比较str1和str2大小, str1==str2则返回0,str1>str2返回大于零的数,否则返回小于零的数
	int res = StringCmp(str1, str2);
	if (res>0)
		printf("str1大于str2\n");
	else if(res<0)
		printf("str1小于str2\n");
	else
		printf("str1等于str2\n");
	return 0;
}

结果:
This is My
This is My CSDN Blog!
len=21
str1大于str2

发布了21 篇原创文章 · 获赞 20 · 访问量 2990

猜你喜欢

转载自blog.csdn.net/weixin_42844163/article/details/104065685
今日推荐