1.Mystrcmp函数,字符串比较 “abc”< “x” ;“abc”== “abc”;“ab” >“aa”
第一个大于第二个则返回正数,相等返回0,第一个小于第二个返回负数。
#include<stdio.h>
#include<assert.h>
int Mystrcmp(const char *str1,const char *str2)
{
assert(str1!=NULL && str2!=NULL);
if(str1==NULL || str2==NULL)
{
return 0;
}
int tmp=0;
while((tmp=*str1-*str2)==0&&*str1!='\0')
{
str1++;
str2++;
}
return tmp;
}
int main()
{
printf("%d\n",Mystrcmp("abc","abc"));
printf("%d\n",Mystrcmp("abc","x"));
printf("%d\n",Mystrcmp("ab","aa"));
return 0;
}
运行结果如下:
2.Myatoi函数
将字符串转成数字,“123”->123
#include<stdio.h>
#include <ctype.h>
#include<assert.h>
int Myatoi(const char *str)
{
assert(str!=NULL);
if(str==NULL)
{
return 0;
}
int tmp=0;
int flg=1;
if(*str==' '||*str=='+') //处理空格和“+”
{
str++;
}
if(*str=='-') //处理负数
{
flg=-1;
str++;
}
while(isdigit(*str))
{
tmp=tmp*10+*str-'0';
str++;
}
return tmp*flg;
}
int main()
{
printf("%d\n",Myatoi("123")); //测试用例
printf("%d\n",Myatoi("-123"));
printf("%d\n",Myatoi("+123"));
printf("%d\n",Myatoi("asdf"));
printf("%d\n",Myatoi("156s4"));
return 0;
}
运行结果如下:
3.Myitoa函数,数字转字符
#include<stdio.h>
#include<string.h>
#include<assert.h>
void ReverseStr(char *str) //逆序输出
{
int j=strlen(str)-1; //字符串最后一位是'\0','\0'不能放到最前面
int tmp;
for(int i=0;i<j;i++,j--)
{
tmp=str[i];
str[i]=str[j];
str[j]=tmp;
}
}
void Myitoa(char *buf,int n) //数字转字符
{
assert(buf!=NULL);
if(buf==NULL)
{
return ;
}
int i=0;
//123->"321"
while(n!=0)
{
buf[i++]=n%10+'0';
n/=10;
}
buf[i]='\0';
ReverseStr(buf);
}
int main()
{
char buf[200];
Myitoa(buf,123); //测试用例
printf("%s\n",buf);
return 0;
}
运行结果如下: