输出有问题,不知道错在哪
#include
using namespace std;
typedef struct {
char* ch;
int length;
}HString;
bool InitHstring(HString& L) {
L.ch = NULL;
L.length = 0;
return true;
}
bool StrAssign(HString& L, char* s) {
if (L.ch != NULL) {
delete L.ch;
L.ch = NULL;
}
int i;
char* c;
for (i = 0, c = s; *c; i++, c++);
if (!i) {
L.length = 0;
L.ch = NULL;
}
else {
L.length = i;
L.ch = new char[i + 1];
if (L.ch)return false;
for (int j = 0; j < i; j++) {
L.ch[j] = s[j];
}
L.ch[i] = '\0';
}
return true;
}
bool StrDelete(HString& L, int pos, int len) {
if (len < 0 || pos<0 || pos + len>L.length)
return false;
for (int i = pos + len; i < L.length; i++)
L.ch[i - len] = L.ch[i];
L.length -= len;
L.ch[L.length] = '\0';
return true;
}
bool Getnextval(HString L, int* nextval) {
int i = 0, j = -1;
nextval[0] = -1;
while (i < L.length - 1) {
if (j == -1 || L.ch[i] == L.ch[j]) {
i++; j++;
if (L.ch[i] == L.ch[j])nextval[i] = nextval[j];
else nextval[i] = j;
}
else {
j = nextval[j];
}
}
return true;
}
int Index(HString L, HString T, int pos, int* next) {
int i = pos, j = 0;
while (j < T.length && i < L.length) {
if (L.ch[i] == T.ch[j] || j == -1) {
i++; j++;
}
else {
j = next[j];
}
}
if (j >= T.length)return i - T.length;
else return -1;
}
bool Index_Delete(HString& L, HString T, int pos) {
int* next = new int[T.length + 1];
Getnextval(T, next);
int k = Index(L, T, pos, next);
while (k >= 0) {
StrDelete(L, k, T.length);
pos = k;
k = Index(L, T, pos, next);
}
return true;
}
bool Display(HString L) {
cout << L.ch << endl;
return true;
}
int main() {
char s[] = "abc12abcd123efdk1123";
char h[] = "12";
HString S, T;
InitHstring(S);
InitHstring(T);
StrAssign(S, s);
cout << "主串串值为:" << endl;
Display(S);
StrAssign(T, h);
cout << "模式串串值为:" << endl;
Display(T);
int pos = 0;
Index_Delete(S, T, pos);
cout << "删除后的主串值为:" << endl;
Display(S);
return 0;
}
你可以对比下我博客中的KMP算法,不一样的理解方式,但是是c去写的