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);
}