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.
请按任意键继续. . .
- C strcmp 与 strncmp
- C strcmp 与 strncmp
- C++:strcmp与strncmp的比较
- strcmp 与strncmp
- strcmp与strncmp区别
- strcmp与strncmp的区别
- strcmp与strncmp的区别
- strcmp与strncmp的区别
- strcmp与strncmp的区别
- strcmp() , strncmp();
- 区分strcmp 与strncmp 、strcpy与strncpy
- C语言 模拟实现strcmp strncmp
- 【C语言】模拟实现strcmp()、strncmp()函数
- strlen,与字符数组,memcpy,strcmp,strncmp
- strcmp与strncmp()的用法
- 【面试题】C语言:模拟实现memcmp,试比较memcmp与strcmp,strncmp的区别
- C中的strcpy()、strcat()、strcmp()、strncpy()、strncat()、strncmp()
- 利用c语言函数调用写strcmp,strncmp
- C++(Singleton)更高效单例模式实现
- [hihocoder]:1048 状态压缩二(状压DP)
- “爆炸门”苹果补刀,三星该“哭晕了”!
- Button、ImageView、RadioButton、CheckBox、AutoCompleteTextView简单使用
- Javaの路
- C strcmp 与 strncmp
- BNU19323 UVA10905 Children's Game
- 数据结构实验之数组三:快速转置
- 欢迎使用CSDN-markdown编辑器
- POJ 3164 有向图的最小生成树
- Java关键字介绍
- java学习
- 【并行计算-CUDA开发】CUDA bank conflict in shared memory
- one