串:即字符串;
字串:串中任意个连续字符组成的子序列;
1.串的顺序存储
(1)静态数组实现(定长顺序存储):
#define MAXLEN 255
Typedef struct{
char ch[MAXLEN];
int length;
}SString;
(2)动态数组实现(堆分配存储):
Typedef struct{
char *ch;//按串长分配存储区,ch指向串的基地址
int length;
}HString;
HString S;
S.ch=(char*)malloc(MAXLEN*sizeof(char));//需要手动free
S.length=0;
2.串的链式存储
(1)低密度
typedef struct StringNode{
char ch;
struct StringNode* next;
}StringNode,* String;//存储密度低,每个字符1B,每个指针4B
(2)高密度
typedef struct StringNode{
char ch[4];
struct StringNode* next;
}StringNode,* String;//存储密度提高
3.串的基本操作
(1) 求子串
SubString(&Sub,S,pos,len)://求子串,用Sub返回S的第pos个字符起长度为len的子串
#define MAXLEN 255
typedef struct{
char ch[MAXLEN];
int length;//串的实际长度
}SString;
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;
}
(2)比较操作
StrCompare(S,T): 比较操作,若S>T,则返回值>0;若S=T,则返回值=0;若S<T,则返回值<0;
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); //扫描过的字符都相同,则长度长的串更大;
}
(3)定位操作
Index(S , T): 定位操作,若主串S中存在与T值相同的子串,则返回它在主串S中第一次出现的位置;否则函数值为0;
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){ //将取到的子串与T比较,不相等就继续取子串
++i;
}
else
return i; //返回子串在主串中的位置
}
return 0; //S中不存在与T相等的子串
}