C語言比較字串範例

2019-10-16 22:09:24

在C語言中,如何比較字串?建立一個原始檔:program_to_compare_strings.c,參考以下實現程式碼 -

#include <stdio.h>

int main() {
   char s1[] = "advise";     
   char s2[] = "advice";

   int n = 0;
   unsigned short flag = 1; 

   while (s1[n] != '\0') {
      if(s1[n] != s2[n]) {
         flag = 0;
         break;
      }
      n++;
   }

   if(flag == 1) {
      printf("%s and %s are identical\n", s1, s2);
   }else {
      printf("%s and %s are NOT identical\n", s1, s2);
   }

   return 0;
}

執行上面範例程式碼,得到以下結果 -

advise and advice are NOT identical