数据结构串 堆串基本操作C语言实现

【数据结构】串 堆串的基本操作

以一组地址连续的存储单元存放串值字符序列,存储空间在程序执行过程中动态分配得到,操作灵活。

代码:

1.结构体定义
typedef struct {
	char * ch;	//若是非空串,则按串长分配存储区,否则ch为NULL
	int length; //串长度
}HString;
2.基本操作函数声明
// 基本操作的函数原型说明

//初始化生成一个空串T
Status StrInit(HString &T);

//生成一个其值等于串常量chars的串T
Status StrAssigh(HString &T, char * chars);

//返回S的元素个数,称为串的长度
int StrLength(HString S);

//若S>T,则返回值大于0....
Status StrCompare(HString S, HString T);

//将S清为空串,并释放S所占空间 
Status ClearString(HString &S);

//用T返回由S1和S2联接而成的新串
Status Concat(HString &T, HString S1, HString S2);

//返回串S的第pos个字符起长度为len的子串
Status SubString(HString &Sub,HString S, int pos, int len);
3.函数定义
#include "String.h"

Status StrInit(HString & T)
{
	T.ch = NULL;
	T.length = 0;
	return OK;
}

Status StrAssigh(HString & T, char * chars)
{
	if (T.ch)free(T.ch);		//释放其原有空间
	char* c = chars; int i = 0;
	for (i = 0; *c; i++, ++c); //求chars的长度i
	if (!i) {
		T.ch = NULL;
		T.length = 0;
	}
	else {
		if (!(T.ch = (char*)malloc(i * sizeof(char)))) exit(OVERFLOW);
		for (int  j = 0; j < i; j++)T.ch[j] = chars[j];
		T.length = i;
	}
	return OK;
}


int StrLength(HString S)
{
	return S.length;
}

Status StrCompare(HString S, HString T)
{
	for (int i = 0; i < S.length&&i<T.length; i++)
		if (S.ch[i] != T.ch[i])return S.ch[i] - T.ch[i];
	return S.length - T.length;
}

Status ClearString(HString & S)
{
	if (S.ch) {
		free(S.ch); S.ch = NULL;
	}
	S.length = 0;
	return OK;
}

Status Concat(HString & T, HString S1, HString S2)
{
	if (T.ch) free(T.ch);	//释放旧空间
	if (!(T.ch = (char*)malloc((S1.length + S2.length) * sizeof(char))))
		exit(OVERFLOW);
	for (int i = 0; i < S1.length; i++) T.ch[i] = S1.ch[i];
	T.length = S1.length + S2.length;
	for (int i = S1.length; i < T.length; i++) T.ch[i] = S2.ch[i-S1.length];
	return OK;
}

Status SubString(HString &Sub,HString S, int pos, int len)
{
	if (pos<1 || pos>S.length || len<0 || len>S.length - pos + 1)return ERROR;
	if (Sub.ch) free(Sub.ch);			//释放旧空间
	if (!len) {
		Sub.ch = NULL; Sub.length = 0;
	}
	else {
		Sub.ch = (char*)malloc(len * sizeof(char));
		for (int i = 0; i < len; i++)
		{
			Sub.ch[i] = S.ch[pos - 1 + i];
		}
		Sub.length = len;
	}
	return OK;
}

4.测试
#include"String.h"
using namespace std;

void StrDisplay(HString S) {
	//显示串
	for (int i = 0; i < S.length; i++)
	{
		cout << S.ch[i];
	}
}
int main() {
	HString A;
	StrInit(A);
	HString B;
	StrInit(B);
	HString C;
	StrInit(C);
	char b[10] = "hello";
	char c[10] = " world";

	cout << "初始化B,显示B:" << endl;
	StrAssigh(B, b);
	StrDisplay(B);

	cout << endl<<"初始化C,显示C:" << endl;
	StrAssigh(C, c);
	StrDisplay(C);
	
	cout << endl << "比较串B,C,返回一个数值" << endl;
	cout << StrCompare(A, B);
	
	cout << endl<<"将B,C串联接成串A,输出A:" << endl;
	Concat(A, B,C);
	StrDisplay(A);

	cout << endl << "输出串A第二个字符起后五个字符" << endl;
	SubString(B, A, 2, 5);
	StrDisplay(B);
	cout << endl << "串长度为";
	cout << StrLength(B);
	
	cout << endl;
	system("pause");

}

测试结果:
数据结构串 堆串基本操作C语言实现_第1张图片

你可能感兴趣的:(数据结构严蔚敏,数据结构,堆串,C语言实现)