C語言中的strcmp()函式是什麼?


C庫函式 **int strcmp(const char *str1, const char *str2)** 將由 **str1** 指向的字串與由 **str2** 指向的字串進行比較。

字元陣列稱為字串。

宣告

以下是陣列的宣告:

char stringname [size];

例如:char string[50]; 長度為50個字元的字串

初始化

  • 使用單字元常量:
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • 使用字串常量:
char string[10] = "Hello":;

**訪問**:使用控制字串“%s”訪問字串,直到遇到‘\0’。

strcmp()函式

  • 此函式比較兩個字串。

  • 它返回兩個字串中前兩個不匹配字元的ASCII碼差值。

字串比較

語法如下:

int strcmp (string1, string2);

如果差值為零 ------ string1 = string2

如果差值為正 ------ string1 > string2

如果差值為負 ------ string1 < string2

示例程式

以下程式演示了strcmp()函式的用法:

 線上演示

#include<stdio.h>
main ( ){
   char a[50], b [50];
   int d;
   printf ("enter 2 strings:
");    scanf ("%s %s", a,b);    d = strcmp (a,b);    if (d==0)       printf("%s is equal to %s", a,b);    else if (d>0)       printf("%s is greater than %s",a,b);    else if (d<0)       printf("%s is less than %s", a,b); }

輸出

執行上述程式後,會產生以下結果:

enter 2 strings:
bhanu
priya
bhanu is less than priya

讓我們看另一個關於strcmp()的例子。

以下是使用strcmp庫函式比較兩個字串的C程式:

示例

 線上演示

#include<stdio.h>
#include<string.h>
void main(){
   //Declaring two strings//
   char string1[25],string2[25];
   int value;
   //Reading string 1 and String 2//
   printf("Enter String 1: ");
   gets(string1);
   printf("Enter String 2: ");
   gets(string2);
   //Comparing using library function//
   value = strcmp(string1,string2);
   //If conditions//
   if(value==0){
      printf("%s is same as %s",string1,string2);
   }
   else if(value>0){
      printf("%s is greater than %s",string1,string2);
   }
   else{
      printf("%s is less than %s",string1,string2);
   }
}

輸出

執行上述程式後,會產生以下結果:

Enter String 1: Tutorials
Enter String 2: Point
Tutorials is greater than Point

更新於:2021年3月19日

653 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告