编写字符串比较函数mystrcmp,其功能:对两个字符串进行比较,若这两个字符串相等,则返回0,并若这两个字符串不相等,则返回它们第一个不同字符的ASCII码差。
#include<stdio.h>
#include<string.h>
int compare(char*, char*);
int main()
{
int a;
char str1[100], str2[100];
printf("请输入两个字符串\n");
gets_s(str1);
gets_s(str2);
a=compare(str1, str2);
printf("\n%d", a);
return 0;
}
int compare(char str3[], char str4[])
{
int b;
char *p = str3;
char *q = str4;
while(*p==*q)
{
p++;
q++;
b = 0;
}
if(*p>*q)
{
b = 1;
}
else
{
b = -1;
}
switch (b)
{
case 1:
printf("str1>str2");
break;
case 0:
printf("str1=str2");
break;
case-1:
printf("str1<str2");
break;
}
int t=*p-*q;
return t;
}
核心代码:
while(*p==*q)
{
p++;
q++;
b = 0;
}
if(*p>*q)
{
b = 1;
}
else
{
b = -1;
}
int t=*p-*q;
核心功能:指针传参
总结:
1.有(返回)类型的函数(主函数除外)必须返回对应类型的值。
2.字符串的比较:①a>A②B>A③a-A=32。
3.指针定义时一定要初始化(有指向)。
心得:
阿巴啊巴,终于整好了,学会了。Happy!C语言道阻且长啊!
奥利给!!!
Author:Jeams Dean
Date;2021.4.2