用 strncmp 庫函式編寫一個 C 程式來比較兩個字串


Strncmp 是 string.h 檔案中預定義的庫函式, 用於比較兩個字串並顯示哪個字串更大。

strcmp 函式(字串比較)

此函式比較兩個字串。它返回兩個字串中前兩個不匹配字元的 ASCII 差異。

語法

int strcmp (string1, string2);
  • 如果差異等於零, 則字串 1 = 字串 2。

  • 如果差異為正數, 則字串 1 > 字串 2。

  • 如果差異為負數, 則字串 1 < 字串 2。

示例

strncmp 函式

此函式用於比較兩個字串的前“n”個字元。

語法

strncmp ( string1, string2,2)

程式

#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 = strncmp(string1,string2,4);
   //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

更新於: 06-03-2021

3000+ 瀏覽量

開啟您的 職業生涯

完成課程獲得認證

開始
廣告