第四章串——4.2:串的表现和实现
我们对于串的定长顺序表示如下
#define chushi 255
typedef unsigned char sstring[chushi + 1];
例4.2我们首先进行串的连接
Status concat(sstring& t, sstring s1, sstring s2)
{
if (s1[0] + s2[0] <= chushi)
{
t[1..s1[0]] = s1[1..s1[0]];
t[s1[0] + 1..s2[0]] = s2[1..s2[0]];
t[0] = s1[0] + s2[0];
uncut = true;
}
else if (s1[0] < chushi)
{
t[1..s1[0]] = s1[1..s1[0]];
t[s1[0] + 1..chushi] = s2[1..shushi - s1[0]];
t[0] = chushi;
uncut = fault;
}
else
{
t[0..chushi] = s1[0..chushi];
uncut = fault;
}
return fault;
}
求子串
Status substring(sstring& sub, sstring s, int pos, int len)
{
if (pos<1 || pos>s[0] || len<0 || len>s[0] - pos + 1)
return error;
sub[1..len] = s[pos..pos + len - 1];
sub[0] = len;
return ok;
}
为避免串的长度有上限的问题,我们使用段的堆分配存储
typedef struct
{
char* ch;
int length;
}hstring;
例4.4在串s的第pos个字符前插入串t
Status strinsert(hstring& s, int pos, hstring t)
{
if (pos<1 || pos>s.length + 1)return error;
if (t.length)
{
if (!(s.ch = (char*)realloc(s.ch, (s.length + t.length) * sizeof(char))))
exit(overflow);
for (i = length - 1; i >= pos - 1; --i)
s.ch[i.t.length] = s.ch[i];
s.ch[pos - 1..pos_t.length - 2] = t.ch[0..t, length - 1];
s.length += t.length;
}
return ok;
}
下面是一些串的堆分配的基本函数
生成一个值为chars的串t
Status strassign(hstring& t, char* chars)
{
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);
t.ch[0..i - 1] = chars[0..i - 1];
t.length = i;
}
return ok;
}
返回s的长度
int strlength(hstring& s)
{
return t.length;
}
若s>t返回值>0,
int strcompare(hstring s, hstring t)
{
for (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;
}
将s清空
Status clearstring(hstring& s)
{
if (s.ch)
{
free(s.ch);
s.ch = NULL;
}
s.length = 0;
return ok;
}
返回s1和s1组成的新串
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)))
exir(overflow);
t.ch[0..s1.length - 1] = s1.ch[0..s1.length - 1];
t.length = s1.length + s2.length;
t.ch[s1.length - 1..t.length - 1] = s2.ch[0..s2.length - 1];
return ok;
}
用sub返回s的dipos字符起长度为len的串
Status substring(Hstring& sub, hstring s, int pos, int len)
{
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));
sub.ch[0..len - 1] = s.ch[pos - 1..pos + len - 2];
sub, length = len;
}
return ok;
}
串还有块链存储
#define chushi 80
typedef struct chunk
{
char ch[chushi];
struct chunk* next;
}chunk;
typedef struct
{
chunk* head, * tail;
int curlen;
}lstring;