1. 程式人生 > >19.在指定的字串陣列中查詢給定的字串

19.在指定的字串陣列中查詢給定的字串

給定程式中,函式fun的功能是:在形參ss所指字串陣列中查詢與形參t所指字串相同的串,找到後返回該字串在字串陣列中的位置,未找到則返回-1,ss所指字串陣列中共有N個內容不同的字串,且串長小於M。

#include<stdio.h>
#include<string.h>
#define N 5
#define M 8
int fun(char (*s)[M], char *t)
{
	int i;
	for (i = 0;i < N;i++)
		if (strcmp(s[i], t) == 0)
		return i+1;
	return -1;

}
int main()
{
	char ch[N][M] = { "if","while","switch","int","for" }, t[M];
	int n, i;
	printf("\nThe original string \n\n");
	for (i = 0;i < N;i++)
		puts(ch[i]);
	printf("\n");
	printf("\nEnter a string for search: ");
	gets(t);
	n = fun(ch, t);
	if (n == -1)
		printf("\nDonot found!\n");
	else
		printf("\nThe position is %d.\n", n);
	getchar();
	return 0;
}