串的定义
串是由零个或多个字符组成的有限序列。
串中字符的个数称为串的长度。
零个字符的串称为空串。
串中任意个连续字符组成的子序列称为该串的子串。
包含子串的串相应地称为主串。
串的逻辑结构和线性表类似,串是限定了元素为字符的线性表。
串的存储结构
-
定长顺序存储表示
#define maxSize 100 typedef struct { char str[maxSize + 1]; int length; }Str;
-
变长分配存储表示
typedef struct{ char *ch; int length; }Str;
串的基本操作
以变长串为例;
//赋值操作
int strassign(Str& str, char *ch){
if(str.ch)
free(str.ch);
int len = 0;
char *c = ch;
while(*c){
++len;
++c;
}
if(len == 0){
str.ch = NULL;
str.length = 0;
return 1;
}else{
str.ch = (char *)malloc(sizeof(char)*(len + 1));
if(str.ch == NULL)
return 0;
else{
c = ch;
for(int i = 0; i <= len; ++i, ++c)
str.ch[i] = *c;
str.length = len;
return 1;
}
}
}
//获取串的长度
int strlength(Str str){
return str.length;
}
//串的比较操作
int strcompare(Str s1, Str s2){
for(int i = 0; i < s1.length && i < s2.length; ++i)
if(s1.ch[i] != s2.ch[i])
return s1.ch[i] - s2.ch[i];
return s1.length - s2.length;
}
//串连接操作
int concat(Str& str, Str str1, Str str2){
if(str.ch){
free(str.ch);
str.ch = NULL;
}
str.ch = (char *)malloc(sizeof(char) * (str1.length + str2.length + 1));
if(str.ch == NULL)
return 0;
int i = 0;
while(i < str1.length){
str.ch[i] = str1.ch[i];
++i;
}
int j = 0;
while(j <= str2.length){
str.ch[i + j] = str2.ch[j];
++j;
}
str.length = str1.length + str2.length;
return 1;
}
//求子串操作
int substring(Str &substr, Str str, int pos, int len){
if(pos < 0 || pos >= str.length || len < 0 || len > str.length - pos)
return 0;
if(substr.ch){
free(substr.ch);
substr.ch = NULL;
}
if(len == 0){
substr.ch = NULL;
substr.length = 0;
return 1;
}else{
substr.ch = (char *)malloc(sizeof(char) * (len + 1));
int i = pos;
int j = 0;
while(i < pos + len){
substr.ch[j] = str.ch[i];
i++;
j++;
}
substr.ch[j] = '\0';
substr.length = len;
return 1;
}
}
//串清空操作
int clearstring(Str &str){
if(str.ch){
free(str.ch);
str.ch = NULL;
}
str.length = 0;
return 1;
}
注:上面代码中
if(str.ch) free(str.ch);
如果str.ch
没有进行初始化将会报错。