运行结果:
代码:
#include<cstring>
#include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
#define MAXSTRLEN 255//用户可在255以内定义最长字符串
typedef char SString[MAXSTRLEN + 1];//0号单元存放串的长度
SString S;
Status StrAssign(SString T, char *chars){
//生成一个其值等于chars的串T
int i;
if (strlen(chars) > MAXSTRLEN)
return ERROR;
else{
T[0] = strlen(chars);
for (i = 1; i <= T[0]; i++)
T[i] = *(chars + i - 1);
return OK;
}//else
}
int Index(SString S, SString T, int pos){
//返回字串T在主串S中第pos个字符之后的位置。若不存在,则函数值为0.
//其中T非空,1《pos《StrLength(S).
int i = pos;
int j = 1;
while (i <= S[0] && j <= T[0])
{
if (S[i] == T[j])
{
++i;
++j;
}//if继续比较后继字符
else
{
i = i - j + 2;
j = 1;
}//else指针后退重新开始匹配
}//while
if (j > T[0])
return i - T[0];
else
return 0;
return 0;
}//index
int main()
{
char str[20];
char mo[20];
SString S, T;
cout << "请输入DNA序列" << endl;
cin >> mo;
cout << "请输入病毒序列" << endl;
cin >> str;
StrAssign(S, mo);
StrAssign(T, str);
/*StrAssign(S, "ababcabcacbab");
StrAssign(T, "abcac");*/
cout << "病毒在DNA在第" << Index(S, T, 1) << "个结点处首次匹配\n";
return 0;
}