Skip to content

Latest commit

 

History

History
72 lines (48 loc) · 2.47 KB

46.md

File metadata and controls

72 lines (48 loc) · 2.47 KB

C strcmp()函数

原文: https://beginnersbook.com/2017/11/c-strcmp-function/

strcmp()函数比较两个字符串并根据结果返回一个整数值。

C strcmp()函数声明

int strcmp(const char *str1, const char *str2)

str1 - 第一个字符串

str2 - 第二个字符串

strcmp()的返回值

此函数根据比较结果返回以下值:

  • 0:如果两个字符串相等
  • > 0:如果字符串str1的第一个不匹配字符的 ASCII 值大于字符串str2中的字符
  • < 0:如果字符串str1的第一个不匹配字符的 ASCII 值小于字符串str2中的字符

根据许多在线教程,当第一个字符串大于第二个字符串时,此函数返回正值,这绝对是不是真的,或者你可以说没有正确表达,因为当我们说一个字符串大于第二个字符串时我们在谈论长度。但是,此函数不比较长度,它将第一个字符串的每个字符的 ASCII 值与第二个字符串匹配,如果第一个字符串中第一个不匹配字符的 ASCII 值大于第二个字符串的不匹配字符的 ASCII 值,则返回正数。

让我们举一个例子来理解这一点。

示例:C 中的strcmp()函数

#include <stdio.h>
#include <string.h>

int main () {
   char str1[20];
   char str2[20];
   int result;

   //Assigning the value to the string str1
   strcpy(str1, "hello");

   //Assigning the value to the string str2
   strcpy(str2, "hEllo");

   result = strcmp(str1, str2);

   if(result > 0) {
      printf("ASCII value of first unmatched character of str1 is greater than str2");
   } else if(result < 0) {
      printf("ASCII value of first unmatched character of str1 is less than str2");
   } else {
      printf("Both the strings str1 and str2 are equal");
   }

   return 0;
}

输出:

ASCII value of first unmatched character of str1 is greater than str2

在上面的例子中,我们使用函数strcmp()比较两个字符串str1str2。在这种情况下,strcmp()函数返回一个大于 0 的值,因为第一个不匹配字符'e'的 ASCII 值是 101,它大于'E'的 ASCII 值 69。

相关文章:

  1. C - strcat()示例
  2. C - strncat()示例
  3. C - strchr()示例