天天看點

【C】庫函數之 strcmpCompare two strings

Compare two strings

#include <string.h>
int strcmp ( const char * str1, const char * str2 );
           

Compares the C string str1 to the C string str2.

This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.

This function performs a binary comparison of the characters. For a function that takes into account locale-specific rules, see strcoll.

上述内容是 cplusplus 對 strcmp 函數的介紹,可以看出 strcmp 函數用來比較兩個字元串的大小。

若 str1 指向内容 > str2 指向内容 ,則傳回一個正數;

若 str1 指向内容 < str2 指向内容 ,則傳回一個負數;

若 str1 指向内容 == str2 指向内容 ,則傳回 0。

如果需要 對字元串中指定個數的字元 比較大小,則可以參考 strncmp函數實作

源代碼

/*
* Copyright (c) 2018, code farmer from sust
* All rights reserved.
*
* 檔案名稱:Strcmp.c
* 功能:比較兩字元串的大小
*
* 目前版本:V1.0
* 作者:sustzc
*/

# include <stdio.h>
# include <assert.h>

/*
*	函數名稱:Strcmp
*
*	函數功能:比較兩個字元串的大小
*
*	入口參數:s1, s2
*
*	出口參數:*s1 - *s2
*
*	傳回類型:int
*/

int Strcmp(const char *s1, const char *s2) {
    assert((NULL != s1) && (NULL != s2));
   
    while (('\0' != *s1) && (*s1 == *s2)) {
        ++s1;
        ++s2;
    }
   
    return *s1 - *s2;
}  
   
void test() {
    char str1[] = "ab";
    char str2[] = "abc";
    int ret = Strcmp(str1, str2);
   
    if (ret > 0)
        printf("call Strcmp, str1: %s > str2: %s\n", str1, str2);
    else if (0 == ret)
        printf("call Strcmp, str1: %s == str2: %s\n", str1, str2);
    else
        printf("call Strcmp, str1: %s < str2: %s\n", str1, str2);
}  
   
int main(void)
{  
    test();
   
    return 0;
}
           

輸出結果

call Strcmp, str1: ab < str2: abc

繼續閱讀