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'為止(注意'\0'值為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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM