数据结构之串结构的实现--定长结构(C语言)

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

基本操作

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

代码实现

定长字符串结构定义

typedef struct 
{
	char str[MAXSIZE+1];
	int length;
}String,* pStr;

赋值操作

int strAssign(pStr s, char* ch)
{
	char* c = ch;
	int i = 0;
	s->length = 0;
	while(*c && s->lengthstr[s->length] = *c;
		++c;
		s->length++;
	}
	s->str[s->length+1] = '\0';
	return 0;
}

字符串连接

int canCat(pStr s, pStr s1, pStr s2)
{
	int i = 0;
	if(!s)
		return 0;
	s->length = 0;
	if(s1->length+s2->length < MAXSIZE)  // 不截断
	{
		while(s1->str[i] != '\0')
		{
			s->str[i] = s1->str[i];
			i++;
		}
		i = 0;
		while (s2->str[i] != '\0')
		{
			s->str[s1->length+i] = s2->str[i];
			++i;
		}
		s->length = s1->length + s2->length;
	}
	else if(s1->length + s2->length > MAXSIZE) // 截断S2
	{
		printf(".....\n");
		while(s1->str[i] != '\0')
		{
			s->str[i] = s1->str[i];
			++i;
		}
		s->length = s1->length;
		i = 0;
		while( s->lengthstr[s1->length+i] = s2->str[i];
			s->length++;
			i++;
		}
	}
	else									// 截断S1或s=s1
	{
		while(s->length < MAXSIZE)
		{
			s->str[s->length] = s1->str[s->length];
			s->length++;
		}
	}
	s->str[s->length+1] = '\0';
	return 1;
}

取长度

int getLength(pStr s)
{
	if(!s)
		return -1;
	return s->length;
}

字符串比较

int strCompare(pStr s1, pStr s2)
{
	int i = 0;
	for(i=0; ilength && ilength; ++i)
	{
		if(s1->str[i] != s2->str[i])
			return s1->str[i] - s2->str[i];
	}
	return s1->length - s2->length;
}

求子串

int subString(pStr sub, pStr s, int pos, int len)
{
	int i = 0;
	if(pos<1 || pos>s->length || pos+len>s->length || len<1)
		return 0;
	sub->length = 0;
	while(istr[i] = s->str[pos+i];
		++i;
	} 
	sub->length = i;
	sub->str[sub->length+1] = '\0';
	return 1;
}

输出字符串

int clearString(pStr s)
{
	if(s->length ==0 ||!s)
		return 0;
	s->length = 0;
	return 1;
}

清空操作

int display(pStr s)
{
	int i = 0;
	printf("... shuchu...\n");
	if(!s || s->length==0)
		return 0;
	while(s->str[i]!='\0')
	{
		printf("%c", s->str[i]);
		++i;
	}
	printf("\n");
	return 1;
}

测试代码

#include 
#include "String.h"
int main()
{
	String s, s1, s2;
	strAssign(&s, "Hello world");
	printf("%d..\n", s.length);
	display(&s);
	strAssign(&s1, "my string");
	strAssign(&s2, "my students");
	canCat(&s, &s1, &s2);
	display(&s);
	printf("%d...\n", getLength(&s));
	subString(&s, &s1, 3, 6);
	display(&s);
	printf("%d...%d\n", getLength(&s), s.length);
	clearString(&s);
	display(&s);
	return 0;
}

 写在最后

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

你可能感兴趣的:(数据结构学习)