学习参考: 严蔚敏: 《数据结构-C语言版》
基本操作
代码实现
结构定义:
typedef struct
{
char* ch;
int length;
}*pStr, DynString;
赋值操作
int strAssign(pStr str, char* ch)
{
int i = 0, len = 0;
char* c = ch;
if(str->ch)
free(str->ch);
str->ch = NULL;
str->length = 0;
while(*ch)
{
++len;
++ch;
}
if(len==0)
return 0;
str->ch = (char*)malloc(sizeof(char)*(len+1));
if(str->ch==NULL)
return 0;
for(i; ich[i] = *c;
str->length++;
}
return 1;
}
字符串连接
int strCompare(pStr s1, pStr s2)
{
int i =0;
for(i=0; ilength&& ilength; ++i)
if(s1->ch[i] != s2->ch[i])
return s1->ch[i]-s2->ch[i];
return s1->length - s2->length;
}
取长度
int getLength(pStr str)
{
return str->length;
}
字符串比较
int canCat(pStr str, pStr s1, pStr s2)
{
int i = 0, j=0;
if(str->ch)
{
free(str->ch);
str->ch = NULL;
}
str->ch =(char*)malloc(sizeof(char)*(s1->length+s2->length+1));
if(!str->ch)
return 0;
while(ilength)
{
str->ch[i] = s1->ch[i];
i++;
}
while(jlength)
{
str->ch[i+j] = s2->ch[j];
j++;
}
str->length = s1->length+s2->length;
return 1;
}
求子串
int display(pStr str)
{
int i = 0;
if(str->length==0)
return 0;
while(ilength)
{
printf("%c", str->ch[i]);
++i;
}
printf("\n");
return 1;
}
输出字符串
int subString(pStr sub, pStr s,int pos, int len)
{
int i = 0;
if(pos<0||pos>s->length || len<=0 ||len+pos>s->length)
return 0;
if(sub->ch)
free(sub->ch);
sub->ch = NULL;
sub->ch = (char*)malloc(sizeof(char)*(len+1));
sub->length = 0;
if(!sub->ch)
return 0;
while(ich[i] = s->ch[pos+i];
++i;
}
sub->ch[i]='\0';
sub->length = len;
return 1;
}
清空操作
int clearString(pStr s)
{
if(s->ch)
free(s->ch);
s->ch=NULL;
s->length = 0;
return 1;
}
测试代码
#include
#include "DynString.h"
int main()
{
DynString s, s1, s2;
strAssign(&s, "Hello world");
strAssign(&s1, "My Nomal");
strAssign(&s2, "red world");
canCat(&s, &s1, &s2);
display(&s);
subString(&s, &s2, 4, 5);
display(&s);
clearString(&s);
return 0;
}
写在最后
文章记录本人学习所得, 如有所错误, 欢迎留言指出交流, 大神请键盘下留人 ! ! !