strncmp()可以只比较字符串的前面几个字符。
示例
//Visual Studio中加上这句才可以使用scanf()
//否则只能使用scanf_s()
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdbool.h>
//引入字符串函数string.h
//一些ANSI之前的系统使用strings.h头文件,而
//有些系统可能根本没有字符串头文件。
#include <string.h>
#define LISTSIZE 6
//argc: 参数个数 argv[]: 参数数组
int main(int argc, char *argv[])
{
const char * list[LISTSIZE] = {
"astronomy", "astounding",
"astrophysics", "ostracize",
"asterism", "astrophobia"
};
int count = 0;
int i;
for (i = 0; i < LISTSIZE; i++)
{
//只比较前5个字符
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);
system("pause");
return 0;
}
运行测试