strcmp()C库函数用法及示例

C编程标准库提供 strcmp() 函数以比较两个字符串并返回结果 它们是相同的还是不同的。

null

语法和参数

如前所述 函数接受两个字符数组或字符串参数。

int strcmp (const char* str1, const char* str2);
  • const char*str1是第一个字符串或字符数组,它将与第二个字符串或字符数组进行比较。const主要用于防止更改给定的char数组指针。
  • const char*str2是将与第一个字符串或字符数组进行比较的第二个字符串或字符数组。

返回值

函数的作用是:返回int或integer类型。我们可以得到下面解释的3种类型的返回值。

  • `如果两个字符串相同、相等或相同,则返回0。
  • `负整数`if ASCII值 第一个无与伦比的 字符小于秒
  • `正整数`如果第一个不匹配字符的ASCII值大于第二个

比较两个字符串

在C语言中,我们可以比较用字符数组表示的两个字符串。我们将比较字符串“I love poftut.com”和“I loves poftut.com”。

#include #include int main(){    char str1[] = "I love poftut.com", str2[] = "I loves poftut.com";    int result;    // comparing strings str1 and str2    result = strcmp(str1, str2);    printf("strcmp(str1, str2) = %d", result);    return 0;}

我们将用gcc编译 然后运行二进制文件。

$ gcc strcmp.c -o strcmp$ ./strcmp
Compare Two Strings
比较两个字符串

比较两个字符数组

我们可以比较 两个字符数组,其中

#include #include int main(){  char str1[] = "I love poftut.com", str2[] = "I love poftut.com";  int result;  // comparing strings str1 and str2  result = strcmp(str1, str2);  printf("strcmp(str1, str2) = %d", result);return 0;}

相关文章: 如何将Python字符串转换为List?

Compare Two Char Array
比较两个字符数组

我们可以看到这两个字符数组是相同的,因此返回值将为0并打印到屏幕上。

Compare Two Char Array
比较两个字符数组

字符串不同,第一个字符串更大,返回正值

在本例中,第一个字符串更大,并返回一个正整数,即字符的值。

#include #include int main(){    char str1[] = "abcd", str2[] = "aBcd";    int result;    // comparing strings str1 and str2    result = strcmp(str1, str2);    printf("strcmp(str1, str2) = %d", result);    return 0;}
Strings Are Different and First Is Bigger and Return Positive Value
字符串不同,第一个字符串更大,返回正值

字符串是不同的,第二个是较大的返回负值

在这个例子中, 第二个 字符串更大,并返回一个正整数,即字符的值。

#include #include int main(){    char str1[] = "aBcd", str2[] = "abcd";    int result;    // comparing strings str1 and str2    result = strcmp(str1, str2);    printf("strcmp(str1, str2) = %d", result);}
Strings Are Different and Second Is Bigger Return Negative Value
字符串是不同的,第二个是较大的返回负值

字符串相同,返回0

如果两个字符串相同,strcmp()函数将返回0。

#include #include int main(){    char str1[] = "abcd", str2[] = "abcd";    int result;    // comparing strings str1 and str2    result = strcmp(str1, str2);    printf("strcmp(str1, str2) = %d", result);    return 0;}
Strings Are Same Return 0
字符串相同,返回0
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享