程序功能说明:在输入的字符串中,找到指定字符串“virus”在该字符串中包含子串所有可能性个数。
例如:输入:virusttviruse,输出结果:23。
#include<stdio.h>
#include<string.h>
long f(int n);
//查询匹配的个数
int find(char *arr, char *temp, int len_a, int len_t)
{
long m = 0, n = 0;
//检查异常输入
if (len_a <= 0 || len_t <= 0 || len_a <= len_t)
{
return 0;
}
int count = 0;
int flag = 0;
for (int i = 0; i <= len_a - len_t; i++)
{
flag = 1;
for (int j = 0; j<len_t; j++)
{
if (arr[i + j] == temp[j])
{
flag = 1;
}
else
{
flag = 0;
break;
}
}
if (flag == 1)
{
count++;
}
}
return count;
}
int find_cnt(char *arr, char *temp, int len_a, int len_t)
{
long m = 0, n = 0, cnt = 0;
//检查异常输入
if (len_a <= 0 || len_t <= 0 || len_a <= len_t)
{
return 0;
}
int count = 0;
int flag = 0;
for (int i = 0; i <= len_a - len_t; i++)
{
flag = 1;
for (int j = 0; j<len_t; j++)
{
if (arr[i + j] == temp[j])
{
flag = 1;
}
else
{
flag = 0;
break;
}
}
if (flag == 1)
{
count++;
m = i;
n = len_a - i - 5;
cnt += (m + 1)*(n + 1);
}
}
return cnt;
}
int main()
{
char arr[1024];//字符串
char temp[]="virus";//要查找的子字符串
long comb = 0;
long cn=0;
gets(arr);//录入字符串
int len_a = strlen(arr);//计算字符串长度
int len_t = strlen(temp);//计算字符串长度
int count = find(arr, temp, len_a, len_t);
printf("%d\n", count);
comb = f(count);
cn = find_cnt(arr, temp, len_a, len_t);
cn=cn- comb;
printf("%ld", cn);
return 0;
}
//公共个数
long f(int n)
{
long sum = 1;
if (n == 1)
sum = 0;
else
{
if (n == 2)
sum = 2;
else
{
for (int i = 0; i < n; i++)
sum += i;
}
}
return sum;
}