功 能: 这个函数用来比较s1和s2字符串,这个函数将返回一个值, 它的符号与第一对不同的字符的比较结果相关。 如果两个字符串相等的话,strncmp将返回0。 如果s1是s2的一个子串的话,s1小于s2。此外还有,函数 int strncmp (const char *s1, const char *s2, size_t size) 此函数与strcmp极为类似。不同之处是,strncmp函数是指定比较size个字符。也就是说,如果字符串s1与s2的前size个字符相同,函数返回值为0。
用 法: int strncmp(char *str1, char *str2, int maxlen);
说明:此函数功能即比较
字符串str1和str2的前maxlen个字符。如果前maxlen
字节完全相等,返回值就=0;在前maxlen字节比较过程中,如果出现str1[n]与str2[n]不等,则返回(str1[n]-str2[n])。
Example 1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
#include<string.h>
#include<stdio.h>
intmain(
void
)
{
char
*buf1=
"aaabbb"
,*buf2=
"bbbccc"
,*buf3=
"ccc"
;
intptr;
ptr=
strncmp
(buf2,buf1,3);
if
(ptr>0)
printf
(
"buffer2isgreaterthanbuffer1\n"
);
elseif(ptr<0)
printf
(
"buffer2islessthanbuffer1\n"
);
ptr=
strncmp
(buf2,buf3,3);
if
(ptr>0)
printf
(
"buffer2isgreaterthanbuffer3\n"
);
elseif(ptr<0)
printf
(
"buffer2islessthanbuffer3\n"
);
return
(0);
}
|
1
2
3
|
ouput:
buffer2isgreaterthanbuffer1
buffer2islessthanbuffer3
|
Example 2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
/*strncmpexample*/
#include<stdio.h>
#include<string.h>
intmain()
{
charstr[][5]={
"R2D2"
,
"C3PO"
,
"R2A6"
};
intn;
puts
(
"LookingforR2astromechdroids..."
);
for
(n=0;n<3;n++)
{
if
(
strncmp
(str[n],
"R2xx"
,2)==0)
{
printf
(
"found%s\n"
,str[n]);
}
//return0;//return位置不对哦
}
return0;
}
|
1
2
3
4
|
ouput:
LookingforR2astromechdroids...
foundR2D2
foundR2A6
|