#include < stdio.h >
#include < stdlib.h >
#include "myconst.h"
typedef struct {
char * ch;
int length;
}
HString;
int StrLength(HString S) {
return S.length;
}
Status SubString(HString & Sub, HString S, int pos, int len) {
int i;
if (pos < 1 || pos > S.length || len < 0 || len > S.length - pos + 1) return ERROR;
if (Sub.ch) free(Sub.ch);
if (!len) {
Sub.ch = NULL;
Sub.length = 0;
} else {
Sub.ch = (char * ) malloc(len * sizeof(char));
for (i = 0; i < len; i++) Sub.ch = S.ch[pos - 1 + i];
Sub.length = len;
}
return OK;
}
int StrCompare(HString S, HString T) {
int i;
for (i = 0; i < S.length && i < T.length; ++i) if (S.ch != T.ch) return S.ch - T.ch;
return S.length - T.length;
}
Status StrAssign(HString & T, char * chars) {
int i,
j;
char * c;
if (T.ch) free(T.ch);
for (i = 0, c = chars; * c; ++i, ++c);
if (!i) {
T.ch = NULL;
T.length = 0;
} else {
if (! (T.ch = (char * ) malloc(i * sizeof(char)))) exit(OVERFLOW);
for (j = 0; j < i; j++) T.ch[j] = chars[j];
T.length = i;
}
return OK;
}
int Index(HString S, HString T, int pos) {
int i,
m,
n;
HString sub;
if (pos > 0) {
n = StrLength(S);
m = StrLength(T);
i = pos;
while (i <= n - m + 1) {
SubString(sub, S, i, m);
if (StrCompare(sub, T) != 0)++i;
else return i;
}
}
return 0;
}
void main() {
int i;
char chars1[] = "hfjshfjstringgigjg";
char chars2[] = "string";
HString S,
T;
StrAssign(S, chars1);
StrAssign(T, chars2);
i = Index(S, T, 1);
printf("\n%s\n", chars1);
printf("%s\n", chars2);
printf("weizhi: %d", i);
}
标签:ch,Sub,int,HString,pos,MSPP,length From: https://blog.51cto.com/u_16076050/6195969