C++官网参考链接:https://cplusplus.com/reference/cstring/strncmp/
函数
<cstring>
strncmp
int strncmp ( const char * str1, const char * str2, size_t num );
比较两个字符串的字符
将C字符串str1的最多num个字符与C字符串str2的字符进行比较。
这个函数开始比较每个字符串的第一个字符。如果它们相等,则继续执行以下对,直到字符不同,直到到达一个终止的空字符,或者直到两个字符串中的num个字符匹配,以先发生的情况为准。
形参
str1
要比较的C字符串。
str2
要比较的C字符串。
num
要比较的最大字符数量。
size_t是无符号整型。
返回值
返回一个整数值,表示字符串之间的关系:
return value | indicates |
---|---|
<0 | the first character that does not match has a lower value in str1 than in str2 (第一个不匹配的字符在str1中的值小于str2中的值) |
0 | the contents of both strings are equal (两个字符串的内容相等) |
>0 | the first character that does not match has a greater value in str1 than in str2 (第一个不匹配的字符在str1中的值大于str2中的值) |
用例
/* strncmp example */
#include
#include
int main ()
{
char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
int n;
puts ("Looking for R2 astromech droids...");
for (n=0 ; n<3 ; n++)
if (strncmp (str[n],"R2xx",2) == 0)
{
printf ("found %s\n",str[n]);
}
return 0;
}
输出: