串的堆分配存储表示 方法仍然以一组地址连续的存储单元表示,但它们的存储
空间是在程序执行过程中动态分配的。
堆串类型定义
typedef strcut HString
{
char *ch; //若是非空串,则按串长分配存储区,否则ch为NULL
int length; //串的长度
}HString;
堆串常用基本操作的算法描述
串赋值
int StrAssign(HString &S, char *chars)
{
int i = 0, j;
if (S.ch != NULL)
free(S.ch);
while (chars[i] != '\0')
i++;
if (!i)
{
S.ch = NULL;
S.length = 0;
}
else
{
if (!(S.ch = (char *)malloc(i*sizeof(char))))
exit(OVERFLOW);
for (j=0; j<i; j++)
S.ch[j] = chars[j];
S.length = i;
}
return OK;
}
串清空
int ClearString(HString &S)
{
if (S.ch)
{
free(S.ch);
S.ch = NULL;
}
S.length = 0;
return OK;
}
求串长
int StrLength(HString &S)
{
return (S.length);
}
串比较
int StrCompare(HString S, HString T)
{
int i;
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;
}
串插入
int StrInsert(HString &S, int pos, HString T)
{
int i;
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=S.length; i>=pos; i--)
S.ch[T.length+i] = S.ch[i];
for(i=1; i<=T.length; i++)
S.ch[pos-1+i] = T.ch[i];
S.length = S.length + T.length;
}
retur OK;
}
串连接
int Concat(HString &T, HString S1, HString S2)
{
int i;
if (T.ch)
free(T.ch);
if (!(T.ch = (char*)malloc((S1.length+S2.length)*sizeof(char))))
exit(OWERFLOW);
T.length = S1.length+S2.length;
for (i=0; i<S1.length; i++)
T.ch[i] = S1.ch[i];
for (i=0; i<S2.length; i++)
T.ch[S1.length+i] = S2.ch[i];
return OK;
}
求子串
int SubString(HString &sub, HString S, int pos, int len)
{
int i;
if (pos<1 || pos>S.length || len<0 || len>length-pos+1)
return ERROR;
if (sub.ch)
free(sub.ch);
if (!len)
{
sub.ch = NULL;
sub.length = 0;
}
else
{
sub.ch = (char*)mallco(len*sizeof(char));
if (sub.ch == NULL)
exit(OWERFLOW);
for (i=0; i<len; i++)
sub.ch[i] = S.ch[pos+i];
sub.length = len;
}
return OK;
}
- #include <stdio.h>
- #include <malloc.h>
- #include <stdlib.h>
- typedef struct HString
- {
- char *ch;
- int length;
- }HString;
- int SubString(HString &sub, HString S, int pos, int len)
- {
- int i;
- if (pos<0 || pos>S.length || len>S.length-pos+1)
- return 1;
- if (sub.ch)
- free(sub.ch);
- if (!len)
- {
- sub.ch = NULL;
- sub.length = 0;
- }
- else
- {
- sub.ch = (char*)malloc(len*sizeof(char));
- if (sub.ch == NULL)
- exit(1);
- for (i=0; i<len; i++)
- sub.ch[i] = S.ch[pos+i];
- sub.length = len;
- }
- return 0;
- }
- int main(void)
- {
- int i;
- HString S, sub;
- S.ch = "helloworld!";
- S.length = 11;
- sub.ch = NULL;
- sub.length = 0;
- SubString(sub, S, 5, 5);
- for (i=0; i<5; i++)
- printf("%c", sub.ch[i]);
- printf("\n");
- return 0;
- }