c语言中部分限制字符函数的实现strncmp,strncat,strncpy,strstr,strrstr

1、带限制的字符串比较函数的实现

#include<stdio.h>
 int my_strncmp(char *p, char *q, int n)
 {
 	int count = 0;
 	while ((*p == *q)&&(count < n))
 	{
 		*p++;
 		*q++;
 		count++;
 	}
 	if (*p == *q)
 	{
 		return 0;
 	}
 	else
 	{
 		return (*p-*q);
 	}
 		
 }
 int main()
 {
 	char a[] = "abcdef";
 	char b[] = "abchkhkhk";
 	int ret = strncmp(a, b, 4);
 	/*int ret = my_strncmp(a,b,4);*/
 	if (ret == 0)
 	{
 		printf("a和b相等");
 	}
 	else if (ret > 0)
 	{
 		printf("a比b大");
 	}
 	else
 	{
 		printf("a比b小");
 	}
 	return 0;
 }


2、带限制的字符串追加函数的实现

#include <stdio.h>
 void my_strncat(char *p, const char *q,int n)
 {
 	int count = 0;
 	while (*p)
 	{
 		*p++;
 	}
 	while ((*p++ = *q++)&&(count < n-1))
 	{
 		count++;
 	}
 }
 int main()
 {
 	char a[30] = "hello ";
 	char b[] = "abcdefghijklmnopqrstuvwxyz";
 	int i = 0;
 	my_strncat(a, b, 5);
 	printf("%s",a);
 	return 0;
 }


3、带限制的字符串拷贝函数的实现

#include <stdio.h>
 void my_strncpy(char *p, char *q, int n)
 {
 	int count = 0;
 	while ((*p++ = *q++)&&(count < n-1))
 	{
 		count++;
 	}
 }
 int main()
 {
 	char a[20] = "abcdeilajdkfjkl";
 	char b[] = "fghijsdfsdfsdfses";
 	my_strncpy( a, b, 4);
 	printf("%s",a);
 	return 0;
 }


4、在字符串中找第一次出现的子串

#include<stdio.h>
 #include <string.h>
 char *my_strchr(const char* p, const char *q)
 {
 	while ((*p)&&(*p != *q))
 	{
 		*p++;
 	}
 	while (*p == *q)
 	{
 		
 		*p++;
 		*q++;
 		
 	}
 	if (*q=='\0')
 	{
 		return (char*)p;
 
 	}
 	return NULL;
 		
 	
 	
 	
 }
 int main()
 {
 	char a[] = "theworldisverybeautiful";
 	char *p = my_strchr(a, "world");
 	printf("%s",p);
 	return 0;
 }


5、在字符串中找最后一次出现的子串

#include<stdio.h>
char *my_strrchr(const char *p, const char *q)
{
	char *start = NULL;
	char *last = (char*)p;
	int i = 0;
	while (*p && *q)
	{
		start = (char*)p;
		while((p)&&(q[i])&&(*p == q[i]))
		{
			p++;
			i++;
		}
		if (q[i] == '\0')
		{
			last = start;
		}
		
		p = start + 1;
		i = 0;

	}
	if (*p == '\0')
	{
		return last;
	}
	else
	{
		return NULL;
	}
	
}
int main()
{
	char a[] = "hashdhyshuhysahhhyshkhyshnkhjk";
	char *p = my_strrchr(a, "ys");
	printf("%s",p);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值