strlen.strcpy.strcmp.stratoi.stritoa的自己实现

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

//1.字符串连接
char * Mystrcpy(char *des,const char *src,char *p)
{
	while(*p++ = *src++);      //指针p指向des的'\0'位置,从此处开始复制,即实现了字符串连接
	return des;
}

//2.字符串比较
int Mystrcmp(const char *arr,const char *brr)
{
	int count = 0;
	int tmp = 0;
	int i = 0;
	do
	{
		if(arr[i] > brr[i])
		{
			tmp = 1 ;
			break;
		}
		else if(arr[i] < brr[i])
		{
			tmp = -1;
			break;
		}
		i++;
	}while(arr[i]!='\0');
	return tmp;
}


int main()
{
	char arr[] = "And";
	char brr[] = "Aid";
	printf("%d\n",Mystrcmp(arr,brr));
	
	return 0;
}

//3.将字符串转换成数字
int Obtainnum(const char *arr)      //获得个数
{
	int count = 0;
	while(*arr != '\0')
	{
		count++;
		arr++;
	}
	return count;
}

int Mystratoi(const char *arr)
{
	int count = Obtainnum(arr);
	int sum = 0;
	int t = 1;
	int d;
	for(int i = 1;i<count;i++)
	{
		t *= 10;
	}
	do
	{
		d = *arr-'0';
		sum += d*t;
		t /= 10;
		arr++;
		count--;
	}while(count != 0);

	return sum;
}

//4.将数字转换成字符串
void Myitoa(char *str,int n)
{
	int count = 0;
	int t = n;
	do
	{
		n /= 10;
		count++;
	}while(n != 0);
	str[count] = '\0';

	for(;count-1 >= 0;count--)
	{
		n = t%10;
		str[count-1] = '0'+n;
		t /= 10;
	}
}

//5.计算字符串的有效长度,不包含'\0'
int Mystrlen(const char *str)
{
	assert(str != NULL);
	if(str == NULL)
	{
		return 0;
	}
	int count = 0;
	while(*str != '\0')
	{
		count++;
		str++;
	}

	return count;
}

int main()
{
	char des[20] = "abcd";
	char src[] = "efghasdsa";
	int len_1 = strlen(des);
	int len_2 = strlen(src);
	//printf("%s\n",Mystrcpy(des,src,&des[len_1]));   //字符串连接测试
	//printf("%d\n",Mystrcmp(des,src));   //字符串比较测试
	char arr[] = "1234";               //字符串转换为数字
	//printf("%d\n",Mystratoi(arr));
	char str[10];                                     //数字转换为字符串
	Myitoa(str,12345);
	printf("%s\n",str);
    printf("%d\n",Mystrlen(des));                     //计算字符串有效长度
	
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值