链串
1 //str.h 2 3 #ifndef STR_H 4 #define STR_H 5 #define OK 1 6 #define ERROR 0 7 typedef int Status; 8 typedef struct { 9 char *ch; 10 int length; 11 }HString; 12 13 Status StrAssign(HString &T, char *chars); 14 void StrTraverse(HString T); 15 int StrLength(HString S); 16 int StrCompare(HString S, HString T); 17 Status ClearString(HString &S); 18 Status Concat(HString &T, HString S1, HString S2); 19 HString SubString(HString S, int pos, int len);
//求子串的定位函数
int Index(HString S, HString T, int pos); 20 #endif
//Str.cpp #include"Str.h" #include<iostream> #include<cstdlib> Status StrAssign(HString &T, char *chars) { // if (T.ch) // free(T.ch); int i = strlen(chars); if (!i) { T.ch = NULL; T.length = 0; } else { if (!(T.ch = (char *)malloc(i * sizeof(char)))) exit(OVERFLOW); for (int j = 0; j < i; j++) T.ch[j] = chars[j]; T.length = i; } return OK; } int StrLength(HString S) { return S.length; } int StrCompare(HString S, HString T) { for (int i = 0; i < S.length&&i < T.length; ++i) if (S.ch[i] != T.ch[i]) return S.ch[i] - T.ch[i]; return S.length - T.length; } Status ClearString(HString &S) { if (S.ch) { free(S.ch); S.ch = NULL; } S.length = 0; return OK; } Status Concat(HString &T, HString S1, HString S2) { // if (T.ch) // free(T.ch); if (!(T.ch = (char *)malloc((S1.length + S2.length) * sizeof(char)))) exit(OVERFLOW); for (int i = 0; i < S1.length; i++) T.ch[i] = S1.ch[i]; T.length = S1.length + S2.length; for (int i = S1.length; i < T.length; i++) T.ch[i] = S2.ch[i - S1.length]; return OK; } HString SubString(HString S, int pos, int len) { HString Sub; Sub.ch = NULL; Sub.length = 0; if (pos<1 || pos>S.length || len<0 || len>S.length - pos - 1) { Sub.ch = NULL; Sub.length = 0; return Sub; } if (Sub.ch) free(Sub.ch); if (!len) { Sub.length = 0; Sub.ch = NULL; } else { Sub.ch = (char*)malloc(len * sizeof(char)); for (int i = 0; i < len; i++) Sub.ch[i] = S.ch[pos - 1 + i]; Sub.length = len; } return Sub; } void StrTraverse(HString T) { if (T.length == 0) std::cout << "String empty!"; else { for (int i = 0; i < T.length; i++) std::cout << T.ch[i]; } std::cout << std::endl; }
int Index(HString S, HString T, int pos)
{
int i = pos;
int j = 0;
while (i < S.length&&j < T.length)
{
if (S.ch[i] == T.ch[j])
{
++i; ++j;
}
else
{
i = i - j + 1; j = 0;
}
}
if (j >= T.length)
return i - T.length;
else return 0;
}
//Main #include"Str.h" #include<iostream> using namespace std; int main() { HString T,S,ST; char a[] = "hello"; char b[] = "Hello"; StrAssign(S, b); StrTraverse(S); StrAssign(T, a); StrTraverse(T); cout << "len: " << StrLength(T) << endl; Concat(ST, S, T); StrTraverse(ST); cout << StrCompare(S, T) << endl; ClearString(T); cout << "len: " << StrLength(T) << endl; T=SubString(ST, 3, 5); StrTraverse(T);
cout << Index(ST, T, 1); system("pause"); return 0; }