C语言笔记——字符串函数

字符串函数

模拟实现strstr

char *strstr(char *strDestination,const char *strSource); 
char *my_strstr(const char *str1, const char *str2)
{
	assert(str1 != NULL);
	assert(str2 != NULL);
	if (*str2 == '\0')
	{
		return (char*)str1;
	}
	while (*str1 != '\0')
	{
		const char*p1 = str1;
		const char*p2 = str2;
		while (*p2 != '\0')
		{
			if (*p1 != *p2)
			{
				break;
			}
			else
			{
				*p1++;
				*p2++;
			}
		}
		if (*p2 == '\0')
		{
			return (char*)str1;
		}
		str1++;
	}
}
int main()
{
	char *str1 = "pineapple";
	char *str2 = "apple";
	printf("%s\n", my_strstr(str1, str2));
	return 0;
}

模拟实现strcat

char *strcat(char *strDestination,const char *strSource); 
#include 
#include 
char *my_strcat(char *strDes, const char *strSou)
{
	assert(strDes != NULL && strSou != NULL);
	char *pD = strDes;
	char *pS = strSou;
	while (*pD != '\0')   //找到末尾
	{
		*pD++;
	}
	while (*pS != '\0')    //拷贝
	{
		*pD++ = *pS++;
	}
	*pD = '\0';     //添加末尾\0
	return strDes;
}


int main()
{
	char a[20] = "hello ";
	char *b= "world";
	my_strcat(a, b);
	printf("%s\n", a);
}

模拟实现strcmp

char *strcmp(const char *string1,const char *string2); 
#include 
#include 
int my_strcmp(char *str1, const char *str2)
{
	assert(str1 != NULL && str2!= NULL);
	char *p1= str1;
	char *p2 = str2;
	int ret = 0;
	while (*p1!='\0' || *p2!='\0')
	{
		if (*p1 - *p2 != 0)
			break;
		*p1++;
		*p2++;
	}
	ret = *p1 - *p2;
	return ret;
}

int main()
{
	char *a = "hi ";
	char *b = "world";
	int temp=my_strcmp(a, b);
	if (temp == 0)
		printf("a == b\n");
	else if (temp > 0)
		printf(" a > b \n");
	else if (temp < 0)
		printf(" a < b \n");


}

模拟实现strcpy

char *strcpy(char *strDestination,const char *strSource); 
#include 
#include 
char *my_strcpy(char *strDestination, const char *strSource)
{
	assert(strDestination != NULL && strSource != NULL);   //检查参数
	char *pD = strDestination;    //保护参数
	char *pS = strSource;
	while ( *pS!='\0')
	{
		*pD++= *pS++;
	}
	*pD = '\0';
	return strDestination;
}
int main()
{
	char a[] = "abcd";
	char *b = "123";
	my_strcpy(a, b);
	printf("%s\n",a );
	system("pause");


}

模拟实现strlen

size_t strlen(const char *str);
#include 
#include 
size_t my_strlen(const char *string)
{
	if (*string == '\0')
		return 0;
	else
		return my_strlen(string+1) + 1;
}
int main()
{
	char *string= "abcdef";
	printf("%d\n", my_strlen(string));
	system("pause");
}

你可能感兴趣的:(C语言笔记,字符串)