C语言 · 实现strcmp函数 · 字符串比较

蓝桥杯练习碰到两个此类题了:
算法提高 11-1实现strcmp函数  
时间限制:1.0s   内存限制:256.0MB
    
问题描述
  自己实现一个比较字符串大小的函数,也即实现strcmp函数。函数:int myStrcmp(char *s1,char *s2) 按照ASCII顺序比较字符串s1与s2。若s1与s2相等返回0,s1>s2返回1,s1<s2返回-1。具体来说,两个字符串自左向右逐个字符相比(按ASCII值大小相比较),直到出现不同的字符或遇''为止(注意''值为0,小于任意ASCII字符)。如:
  "A"<"B"
  "a">"A"
  "computer">"compare"
  "hello"<"helloworld"
样例输出
数据规模和约定
  字符串长度<100。
 
 
 
算法提高 字符串比较  
时间限制:1.0s   内存限制:512.0MB
    
独立实现标准字符串库的strcmp函数,即字符串比较函数,从键盘输入两个字符串,按字典序比较大小,前者大于后者输出1,前者小于后者输出-1,两者相等输出0。
样例输入: 
  apple one
样例输出:
  -1
样例输入:
  hello he
样例输出:
  1
样例输入:
  hello hello
样例输出:
  0
 
注:两题代码实现相同。
 
第30行涉及到qsort()函数的用法,可参考我的另一篇:
 
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<math.h>
 4 #include<stdlib.h>
 5 #include<ctype.h>
 6 /*定义一个结构体*/
 7 typedef struct Stu{
 8     char str[100];
 9 }stu;
10 int cmp(const void *a,const void *b){
11     stu c = *(stu*)a;
12     stu d = *(stu*)b;
13     //按姓名字符进行字典排序 
14     if(strcmp(c.str,d.str)>0){
15         printf("-1");
16         return strcmp(c.str,d.str);
17     }else if(strcmp(c.str,d.str)<0){
18         printf("1");
19         return strcmp(c.str,d.str);
20     }else if(strcmp(c.str,d.str)==0){
21         printf("0");
22         return strcmp(c.str,d.str);
23     }
24 }
25 main(){
26     stu st[100];
27     for(int i=0;i<2;i++){
28         scanf("%s",&st[i]);
29     }
30     qsort(st,2,sizeof(st[0]),cmp);
31     return 0;
32 }
原文地址:https://www.cnblogs.com/panweiwei/p/6487120.html