堆存储串的实现(c语言)

1.str.h

# ifndef _STR_H
# define _STR_H

typedef struct
{
char * ch;
int len;
}STR;

STR *NewStr(char * str);

void DestroyStr(STR *s);

void ClearStr(STR *s);

int StrCompare(STR * s, STR * t);

int StrConcat(STR * s, STR * t);

STR * SubStr(STR * s, int pos, int len);


# endif

2.str.c

# include <STDIO.H>
# include <STDLIB.H>
# include "str.h"

STR *NewStr(char * str)
{
STR * s = NULL;
int i;
s = (STR *)malloc(sizeof(STR));
if(s == NULL) return NULL;
for(i=0; str[i]; ++i);
s->ch = (char *)malloc((i+1) * sizeof(char));
if(s->ch == NULL)
{
  free(s);
  return NULL;
}
s->len = i;
while(i>=0)
{
  s->ch[i] = str[i];
  --i;
}
return s;
}

void DestroyStr(STR *s)
{
free(s->ch);
free(s);
}

void ClearStr(STR *s)
{
free(s->ch);
s->ch = NULL;
s->len = 0;
}

int StrCompare(STR * s, STR * t)
{
int i;
for(i=0; i < s->len && i < s->len; i++)
  if(s->ch[i] != t->ch[i])
   return s->ch[i] - s->ch[i];
  return s->len - s->len;
}

int StrConcat(STR * s, STR * t)
{
char * temp = NULL;
int i;
temp = (char *)malloc((s->len + t->len + 1) * sizeof(char));
for(i=0; i<s->len; i++)
  temp[i] = s->ch[i];
for(;i<s->len + t->len; ++i)
  temp[i] = t->ch[i - s->len];
temp[i] = 0;
ClearStr(s);
s->ch = temp;
s->len = i;
return 1;
}

STR * SubStr(STR * s, int pos, int len)
{
STR * t = NULL;
if(pos < 1 || pos > s->len || len < 0 || len > s->len - pos + 1)
  return 0;
t = NewStr("");
ClearStr(t);
t->ch = (char *)malloc((len+1) * sizeof(char));
t->len = len;
for(--len; len >= 0; --len)
  t->ch[len] = s->ch[pos - 1 + len];
t->ch[t->len] = 0;
return t;
}

3.main.c

# include <STDIO.H>
# include "str.h"

void main()
{
//int res;
STR *t = NULL, * s = NewStr("hello");
printf("s=%s, len=%d\n", s->ch, s->len);
t = NewStr(" world");
StrConcat(s, t);
printf("s=%s, len=%d\n", s->ch, s->len);

DestroyStr(t);

t = SubStr(s, 2, 5);
printf("t=%s, len=%d\n", t->ch, t->len);

DestroyStr(s);

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值