• C语言实现strcmp


    注意转化为unsigned char:

    strcmp.h

     1 #ifndef STRCMP_H
     2 #define STRCMP_H
     3 
     4 /***************************************************
     5 功能:比较字符串s1和s2。
     6  一般形式:strcmp(s1,s2)
     7   返回值:
     8     当s1<s2时,返回值<0
     9     当s1=s2时,返回值=0
    10     当s1>s2时,返回值>0
    11 ****************************************************/
    12 
    13 int cat_strcmp(const char *src, const char *dst) {
    14     int ret = 0;
    15 
    16     while (!(ret = (*(unsigned char *)src - *(unsigned char *)dst)) && *dst) 
    17         ++src, ++dst;
    18     
    19     if (ret < 0)
    20         ret = -1;
    21     else if (ret > 0)
    22         ret = 1;
    23     
    24     return ret;
    25 }
    26 
    27 #endif

    main:

     1 #include "strcmp.h"
     2 
     3 
     4 void test_strcmp();
     5 
     6 int main() {
     7     test_strcmp();
     8 
     9     return 0;
    10 }
    11 
    12 void test_strcmp() {
    13     char *s1 = "compare", *s2 = "compase";
    14     printf("%d
    ", cat_strcmp(s1, s2));
    15 
    16     char *s3 = "compare", *s4 = "compar";
    17     printf("%d
    ", cat_strcmp(s3, s4));
    18 
    19     char *s5 = "compar", *s6 = "compare";
    20     printf("%d
    ", cat_strcmp(s5, s6));
    21 
    22     printf("%d
    ", cat_strcmp(s3, s6));
    23 }

    /**
    拓展:
    unsigned char和char:
    http://blog.sina.com.cn/s/blog_5c6f793801019oij.html
    http://blog.csdn.net/world7th/article/details/1543575
    */

  • 相关阅读:
    802.11标准及无线网运行模式
    linux中top命令使用及查看tcp连接
    DNS信息收集命令nslookup
    Openvas安装
    nc高级应用
    poj 1411 Calling Extraterrestrial Intelligence Again(超时)
    poj 1046 Color Me Less
    1215 迷宫
    2666 Accept Ratio(打表AC)
    2021 中庸之道
  • 原文地址:https://www.cnblogs.com/lingshaohu/p/3961156.html
Copyright © 2020-2023  润新知