strcasecmp,strncasecmp函數實現——strings.h庫函數

strcasecmp和strncasecmp函數相當於windows下的stricmp和strnicmp函數!

信息來自RHEL,man page:

STRCASECMP(3)                                  Linux Programmer's Manual                                 STRCASECMP(3)

NAME
       strcasecmp, strncasecmp - compare two strings ignoring case

SYNOPSIS
       #include <strings.h>

       int strcasecmp(const char *s1, const char *s2);

       int strncasecmp(const char *s1, const char *s2, size_t n);

DESCRIPTION
       The  strcasecmp() function compares the two strings s1 and s2, ignoring the case of the characters.  It returns
       an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than,  to  match,
       or be greater than s2.

       The strncasecmp() function is similar, except it compares the only first n bytes of s1.

RETURN VALUE
       The  strcasecmp() and strncasecmp() functions return an integer less than, equal to, or greater than zero if s1
       (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

CONFORMING TO
       4.4BSD, POSIX.1-2001.

函數實現:


strcasecmp()函數實現:


0.功能描述:

功能參照strcmp(傳送門:http://blog.csdn.net/riyadh_linux/article/details/50021381)函數,區別之處在於該函數比對時不區分大小寫。

字符串比較函數,逐字符比較字符串s1(source)和字符串s2(dest)
源字符串大於目標字符串時—-> 返回字符串s1從前往後第一個大於字符串s2的對應字符ASCII差值(爲正)
源字符串小於目標字符串時—-> 返回字符串s1從前往後第一個小於字符串s2的對應字符ASCII差值(爲負)
源字符串等於目標字符串時—-> 返回0

1.原型:

#include <strings.h>

int strcasecmp(const char *s1, const char *s2);

2.參數:

s1即源字符串。
s2目標字符串。

3.實現:


//定義FALSE宏值
#define FALSE       ('Z' - 'A')
#define DIFF_VALUE  ('a' - 'A')

int my_strcasecmp(const char *s1, const char *s2)
{
    int ch1 = 0;
    int ch2 = 0;

    //參數判斷
    if(NULL == s1 || NULL == s2){
        return FALSE;
    }

    //逐個字符查找比對,並記錄差值
    do{
        if((ch1 = *((unsigned char *)s1++)) >= 'A' && ch1 <= 'Z'){
            *s1 += DIFF_VALUE;
        }
        if((ch2 = *((unsigned char *)s2++)) >= 'A' && ch2 <= 'Z'){
            *s2 += DIFF_VALUE;
        }
    }while(ch1 && ch1 == ch2);

    return ch1 - ch2;
}

strncasecmp()函數實現:


0.功能描述:

參照strcasecmp函數,區別之處在於,逐個字符比對,判斷前n個字符。並且當n爲零時,返回爲零

1.原型:

#include <strings.h>

int my_strncasecmp(const char *s1, const char *s2, size_t n)

2.參數:

s1,s2:對應strcasecmp函數
n:用來標示此函數應對比前n個字符

3.實現:


#define DIFF_VALUE ('a' - 'A')
#define FALSE      ('z' - 'A')

int my_strncmp(const char *s1, const char *s2, size_t n)
{
    int ch1 = 0;
    int ch2 = 0;

    if(NULL == s1 || NULL == s2 || 0 > n){
        return FALSE;
    }

    if(0 == n){
        return 0;
    }

    do{
        if((ch1 = *(unsigned char *)s1++) >= 'A' && (ch1 <= 'Z')){
            ch1 += DIFF_VALUE;
        }
        if((ch2 = *(unsigned char *)s2++) >= 'A' && (ch2 <= 'Z'))
    }while(n-- && ch1 && (ch1 == ch2));

    return ch1 - ch2;
}

=============文章結束==============
小菜總結,如有不當,歡迎批評!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章