C语言模拟实现strncpy、strncpy、strncat、strstr和strrstr函数实现

以下是我用C语言模拟实现的部分字符串函数:

1、strncpy函数的实现

 

#include<stdio.h>
#include<assert.h>
#include<iostream>
char*my_strncpy(char*dest, const char*src, int n)
{
	assert(dest != NULL);
	assert(src != NULL);
	int i = 0;
	char *tmp = dest;
	while ((i++<n)&&(*tmp++ = *src++ )!= '\0')
	{
		;
	}
	return dest;
}

int main()
{
	char str1[] = "1234567890";
	char str2[] = "abcde";
	my_strncpy( str1,str2, 6);
	printf("%s\n", str1);
	system("pause");
	return 0;
}

 

 

 

2、strncmp函数的实现

 

#include<stdio.h>
#include<iostream>
#include<assert.h>
int my_strncmp(const char*str1, const char*str2,int n)
{
	assert(str1 != NULL);
	assert(str2 != NULL);
	while ((*str1!='\0')&&(*str2!='\0')&&n)
	{
	   if ((*str1 - *str2) > 0)
			return 1;
	   if ((*str1-*str2)<0)
			return -1;
		str1++;
		str2++;
		n--;
	}
	if (*str1 == '\0'&&*str2 != '\0')
		return -1;
	 if (*str1 != '\0'&&*str2 == '\0')
		return 1;
	return 0;
}
int main()
{
	char str1[] = "abcdef";
	char str2[] = "abcmln";
	int ret = my_strncmp(str1, str2,4);
	printf("%d\n", ret);
	system("pause");
	return 0;
}

 

 

 

 

 

3、strncat函数实现

 

#include<stdio.h>
#include<assert.h>
#include<iostream>
char*my_strncat(const char*src,char*dest, int n)
{
	assert(src != NULL&&dest != NULL);
	char*tmp = dest;
	while (*tmp != '\0')
	{
		tmp++;
	}
	while ((n--) && (*tmp++ = *src++) != '\0')
	{
		;
	}
	return dest;

}
int main()
{
	char str1[20] = "hello ";
	char str2[6] = "word!";
	my_strncat(str2, str1, 2);
	printf("%s\n", str1);
	system("pause");
	return 0;
}


 

 

 

4、strstr函数的实现

 

#include<stdio.h>
#include<assert.h>
#include<string.h>
#include<iostream>
char*my_strstr(char*str1, char*str2)
{
	assert(str1 != NULL&&str2 != NULL);
	int i = 0;
	int j = 0;
	char*ret = 0;
	for (i = 0; str1[i] != 0; i++)
	{
		for (j = 0; str2[j] != 0; j++)
		{
			if (str1[i + j] != str2[j])
			{
				break;
			}
		}
		if (str2[j] == 0)
			return str1 + i;

	}
	return NULL;
}

int main()
{
	char str[] = "abbcdbcdefmln";
	char str1[] = "bcd";
	//char *tmp=my_strstr(str, str1);
	printf("%s", my_strstr(str, str1));
	system("pause");
	return 0;
}

 

5、strrstr函数的实现

 

#include<stdio.h>
#include<assert.h>
#include<iostream>
char*my_strrstr(char*str1, char*str2)
{
	assert(str1 != NULL&&str2 != NULL);
	int i = 0;
	int j = 0;
	char*ret = 0;
	for (i = 0; str1[i] != 0; i++)
	{
		for (j = 0; str2[j] != 0; j++)
		{
			if (str1[i + j] != str2[j])
			{
				break;
			}
		}
		if (str2[j] == 0)
			ret=str1+i;

	}
	return ret;
}

int main()
{
	char str[] = "abbcdbcdefmln";
	char str1[] = "bcd";
	//char *tmp=my_strstr(str, str1);
	printf("%s", my_strrstr(str, str1));
	system("pause");
	return 0;
}

 

 

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值