数据结构之串结构的实现--堆分配结构(C语言)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40411915/article/details/82765537

学习参考: 严蔚敏: 《数据结构-C语言版》

基本操作

  1.  赋值操作
  2. 字符串连接
  3. 取长度
  4. 字符串比较
  5. 求子串
  6. 输出字符串
  7. 清空操作

代码实现

结构定义:

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; i<len; ++i, ++c)
	{	
		str->ch[i] = *c;
		str->length++;
	}
	return 1;
}

字符串连接

int strCompare(pStr s1, pStr s2)
{
	int i =0;
	for(i=0; i<s1->length&& i<s2->length; ++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(i<s1->length)
	{
		str->ch[i] = s1->ch[i];
		i++;
	}
	while(j<s2->length)
	{
		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(i<str->length)
	{
		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(i<len)
	{
		sub->ch[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 <stdio.h>
#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;
}

写在最后

文章记录本人学习所得, 如有所错误, 欢迎留言指出交流, 大神请键盘下留人 ! ! ! 

猜你喜欢

转载自blog.csdn.net/weixin_40411915/article/details/82765537
今日推荐