Common.h
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define NULL 0
typedef int Status;
String.h
#include "Common.h"
#define MAXSTRLEN 255
typedef char SString[MAXSTRLEN + 1];
Status Assign(SString T, char* chars);
int Index(SString S, SString T, int pos);
main.cpp
#include <iostream>
#include "String.h"
using namespace std;
int main()
{
while (1)
{
cout << "请输入主串:"; char s1[1024];cin.getline(s1, 1024);
cout << "请输入子串:"; char s2[1024];cin.getline(s2, 1024);
if(strlen(s1)==0||strlen(s2)==0)
{
cout << "错误:主串和子串都不能是空串..." << endl << endl;
}
else
{
SString S; Assign(S, s1);
SString T; Assign(T, s2);
cout << "主串和子串在第"
<< Index(S, T, 1) << "个字符处首次匹配\n\n";
}
}
return 0;
}
String.cpp
#include "String.h"
#include <iostream>
Status Assign(SString T, char* chars)
{
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;
}
}
int Index(SString S, SString T, int pos)
{
int i = pos;int j = 1;
while(i<=S[0]&&j<=T[0])
{
if (S[i] == T[j]) { ++i;++j; }
else { i = i - j + 2;j = 1;}
}
if (j > T[0])return i - T[0];
else return 0;
}