字符串函数实现(strlen,strcpy,strcmp,strcat,strrev)

声明:以下代码可能并非最佳方法,若有错误疑问欢迎提出!!!

strlen函数

#include<stdio.h>
#include<string.h>

int mylen(char *str)
{
	int cnt=0;
	while(str[cnt]!='\0')
	cnt++;
	return cnt;
}
int main()
{
	char s[]="hello";
	printf("%d\n",mylen(s));
	printf("%d",strlen(s));
	return 0;
}

strcpy函数

#include<stdio.h>
#include<string.h>

char* mycpy(char *p,const char *q)
{
	char *a=p;
	while(*q!=NULL)
	*p++=*q++;
	*p='\0';//p已经移动到最后一位,需要一个变量能找到它的地址,该变量就是a 
	return a;
}
int main()
{
	char q[]="hello";
	char p[]="\0";
	printf("%s\n",mycpy(p,q));
	printf("%s",strcpy(p,q));
	return 0;
}

strcmp函数

/*
主要思想是遍历两个字符串的相同部分,直到不同时比较不同字符的大小; 
*/
#include<stdio.h>
#include<string.h>

int mycmp(char *p,char *q)
{
	while(*p==*q&&*p!='\0')
	{
		p++;
		q++;
	}
	if(*p-*q>0)
	return 1;
	if(*p-*q<0)
	return -1;
	if(*p-*q==0)
	return 0;
}
int main()
{
	char p[]="hello";
	char q[]="hi";
	printf("%d\n",mycmp(p,q));
	printf("%d",strcmp(p,q));
	return 0;
}

strcat函数

#include<stdio.h>
#include<string.h>

char *mycat(char *p,char *q)
{
	char *a=p;
	while(*p!='\0')
	p++;
	while(*q!=NULL)
	*p++=*q++;
	return a;
}
int main()
{
	char q[]="world!!!";
	char p[]="hello ";
	printf("%s\n",mycat(p,q));
//	printf("%s",strcat(p,q));
	return 0; 
}

strrev函数

/*
思路参考顺序链表的逆置函数inversion 
*/
#include<stdio.h>
#include<string.h>

char *myrev(char *str)
{
	int top=0;
	int bottom=-1;
	char *a=str;
	char t;
	while(*a!='\0')
	{
		a++;
		bottom++;
	}
	while(top<bottom)
	{
		t=str[top];
		str[top]=str[bottom];
		str[bottom]=t;
		top++;
		bottom--;
	}
	return str;
}
int main()
{
	char a[]="hello";
	printf("%s\n",myrev(a));
	printf("%s",strrev(a));
	return 0;
}
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YXXYX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值