c語言中strcmp函數,函數原型和函數頭文件


1、函數原型。

#include <stdio.h>

int strcmp(const char *s1, const char *s2) // 函數返回int型,形參為兩個指向char型的指針 
{
    while(*s1 == *s2) //當元素相等時 
    {
        if(*s1 == '\0') // 判斷*s1是否為null,*s1是null意味着兩個字符串相等(說明一直到字符串的末尾都相等) 
            return 0;
        s1++;  // 指針依次后移 
        s2++;
    }
    
    return (unsigned char)*s1 - (unsigned char)*s2; //如果*s1 != *s2,  則用指針指向的*s1的當前字符減去指針指向*s2的當前字符。 
}

int main(void)
{
    char str1[128] = "abcd";
    char str2[128];
    printf("str2: "); scanf("%s", str2);
    
    int tmp = strcmp(str1, str2);  //函數的實參為兩個字符串數組名稱,相當於指向數組的首個元素的指針,(函數間數組的傳遞是以數組的第一個元素的指針進行的。) 
    
    if(tmp > 0)
        puts("str1 is greater than str2.");
    else if(tmp == 0)
        puts("str1 is equal to str2.");
    else
        puts("str1 is less than str2.");
    
    return 0;
}

 

 

2、加載strcmp的頭文件,可以直接調用函數

#include <stdio.h>
#include <string.h> // head file? It can run without loading!!!!!


int main(void)
{
    char str1[128] = "abcd";
    char str2[128];
    printf("str2: "); scanf("%s", str2);
    
    int tmp = strcmp(str1, str2);
    
    if(tmp > 0)
        puts("str1 is greater than str2.");
    else if(tmp == 0)
        puts("str1 is equal to str2.");
    else
        puts("str1 is less than str2.");
    
    return 0;
}

 


免責聲明!

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



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