C++官网参考链接:https://cplusplus.com/reference/cstring/strcmp/
函数
<cstring>
strcmp
int strcmp ( const char * str1, const char * str2 );
比较两个字符串
比较C字符串str1和C字符串str2。
这个函数开始比较每个字符串的第一个字符。如果它们相等,则继续执行以下对,直到字符不同或到达一个终止的空字符为止。
这个函数执行字符的二进制比较。有关考虑特定于区域设置规则的函数,请参阅strcoll。
形参
str1
要比较的C字符串。
str2
要比较的C字符串。
返回值
返回一个整数值,表示字符串之间的关系:
return value | indicates |
---|---|
<0 |
the first character that does not match has a lower value in ptr1 than in ptr2(第一个不匹配的字符在ptr1中的值小于ptr2中的值) |
0 |
the contents of both strings are equal(两个字符串的内容相等) |
>0 |
the first character that does not match has a greater value in ptr1 than in ptr2(第一个不匹配的字符在ptr1中的值大于ptr2中的值) |
用例
#include <stdio.h>
#include <string.h>
int main ()
{
char key[] = "apple";
char buffer[80];
do {
printf ("Guess my favorite fruit? ");
fflush (stdout);
scanf ("%79s",buffer);
} while (strcmp (key,buffer) != 0);
puts ("Correct answer!");
return 0;
}
输出:
另请参考
strncmp Compare characters of two strings (function)
memcmp Compare two blocks of memory (function)
strrchr Locate last occurrence of character in string (function)
strspn Get span of character set in string (function)