1. 程式人生 > >93.計算字串s中所包含t字串的數目

93.計算字串s中所包含t字串的數目

函式fun的功能是:計算s所指字串中含有t所指字串的數目,並作為函式的返回值。

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#define N 80
int fun(char *s, char *t)
{
	int n;
	char *p, *r;
	n = 0;
	while (*s)
	{
		p = s;
		r = t;
		while (*r)
		{
			if (*r == *p)
			{
				r++;
				p++;
			}
			else
				break;
		}
		if (*r == 0)
			n++;
		s++;
	}
	return n;
}
int main()
{
	char a[N], b[N];
	int m;
	printf("Please enter string a : ");
	gets(a);
	printf("\nPlease enter substring b :");
	gets(b);
	m = fun(a, b);
	printf("\nThe result is: m=%d\n", m);
	system("pause");
	return 0;
}