一、顺序存储
#define MAXLEN 255
typedef struct{
char ch[MAXLEN];
int length;
}SString;
typedef struct{
char *ch;
int length;
}HString;
HString S;
S.ch = (char *)malloc(MAXLEN *sizeof(char));
S.length = 0;
二、链式存储
typedef struct StringNode{
char ch;
struct StringNode * next;
}StringNode,* String;
typedef struct StringNode{
char ch[4];
struct StringNode * next;
}StringNode,* String;
三、基于顺序存储实现基本操作
1.StrAssign(&T,chars):赋值操作。把串T赋值为chars
2.StrCopy(&T,S):复制操作。由串S复制得到串T
3.StrEmpty(S):判空操作。若S为空串,则返回true,否则返回false
4.StrLength(S):求串长。返回串S的元素个数
5.ClearString(&S):清空操作。将S清为空串
6.DestoryString(&S):销毁串。将串S销毁(回收存储空间)
7.Concat(&T,S1,S2):串联接。用T返回由S1和S2联接而成的新串
bool SubString(SString &Sub,SString S,int pos,int len){
if(pos+len-1>S.length)
return false;
for(int i=pos;i<pos+len;i++)
Sub.ch[i-pos+1] = S.ch[i];
Sub.length = len;
return true;
}
int StrCompare(SString S,SString T){
for(int i = 1;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;
}
int Index(SString S,SString T){
int i = 1,n = StrLength(S),m = StrLength(T);
SString sub;
while(i<=n-m+1){
SubString(Sub,S,i,m);
if(StrCompare(Sub,T)!=0)
++i;
else
return i;
}
return 0;
}