C strcmp 与 strncmp

来源:互联网 发布:mac股票软件 编辑:程序博客网 时间:2024/05/01 09:39

strcmp是常见的字符串比较函数,如果两个字符串参数相同,改函数就返回0,否则返回非零值。

看以下程序:

#include<stdio.h>
#include<string.h>
#define ANSWER "Grant"
#define SIZE 40
char * s_gets(char * st, int n);
int main()
{
char try[SIZE];
puts("Who is buried in Grand's tomb?");
s_gets(try, SIZE);
while(strcmp(try,ANSWER)!=0)
{
puts("No,that's wrong.Try again.");
s_gets(try, SIZE);
}
puts("That's right!");
return 0;
}
char * s_gets(char * st, int n)
{
char * ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
while (st[i] != '\n'&&st[i] != '\0')
i++;
if (st[i] == '\n')
st[i] = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}

结果如下:

Who is buried in Grand's tomb?
asd
No,that's wrong.Try again.
Grant
That's right!
请按任意键继续. . .

strcmp()函数比较字符串中的字符,直到发现不同的字符为止,这一过程可能持续到字符串末尾。而strncmp则可以在比较字符串时,比较到第三个参数指定的字符数。

看以下程序:

#include<stdio.h>
#include<string.h>
#define LISTSIZE 6
int main()
{
const char * list[LISTSIZE] = {
"astronomy","astounding",
"astrophysics","ostracize",
"asterism","astrophobia"
};
int count = 0;
int i;
for (i = 0;i < LISTSIZE; i++)
if (strncmp(list[i], "astro", 5) == 0)
{
printf("Found: %s\n", list[i]);
count++;
}
printf("The list contained %d words beginning with astro.\n", count);
return 0;
}

结果如下:

Found: astronomy
Found: astrophysics
Found: astrophobia
The list contained 3 words beginning with astro.
请按任意键继续. . .

0 0