数据结构 串的堆分配及基本操作

本文介绍了一个使用堆分配内存实现字符串操作的C++程序。该程序实现了字符串的赋值、求长度、比较、连接及子串提取等功能,并通过具体示例展示了如何使用这些函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

堆分配

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
#define TRUE 1
#define FALSE 0
#define  OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef struct{
	char *ch;
	int length;
}hstring;

int strassign(hstring &T, char *chars)
{
	int i, j;
	i = strlen(chars);
	if (i == 0)
	{
		T.ch = NULL;
		T.length = 0;
	}
	else
	{
		T.ch = (char *)malloc(i*sizeof(char));
		for (j = 0; j < i; j++)
			T.ch[j] = chars[j];
		T.length = i;
	}
	return OK;
}

int sstrlength(hstring s)
{
	return s.length;
}

int strcompare(hstring s, hstring T)
{
	int i;
	for (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;
}

int concat(hstring &T, hstring s1, hstring s2)
{
	int i, j;
	T.ch = (char *)malloc((s1.length + s2.length)*sizeof(char));
	for (i = 0; i < s1.length; i++)
		T.ch[i] = s1.ch[i];
	for (i = s1.length; i < s1.length + s2.length; i++)
		T.ch[i] = s2.ch[i - s1.length];
	T.length = s1.length + s2.length;
	return OK;
}

int substring(hstring &sub, hstring s, int pos, int len)
{
	int i;
	if (pos<1 || pos>s.length || len<0 || len>s.length - pos + 1)
		return ERROR;
	if (len == 0)
	{
		sub.ch = NULL;
		sub.length = 0;
	}
	else
	{
		sub.ch = (char *)malloc(len*sizeof(char));
		for (i = 0; i < len; i++)
			sub.ch[i] = s.ch[i+pos-1];
		sub.length = len;
	}
	for (i = 0; i < len; i++)
		cout<<sub.ch[i];
	return OK;
}

void shuchu(hstring s)
{
	int i;
	for (i = 0; i < s.length; i++)
		cout << s.ch[i];
}
int main()
{
	hstring T, s1, s2, sub;
	char *chars1 = "abcde", *chars2 = "jikei";
	int m, n;
	cout << "将chars1的值赋予s1:";
	strassign(s1, chars1);
	shuchu(s1);
	cout << endl;
	cout<<"s1的长度为:"<<sstrlength(s1)<<endl;
	cout << "将chars1的值赋予s1:";
	strassign(s2, chars2);
	shuchu(s2);
	cout << endl;
	cout << "s2的长度为:"<<sstrlength(s2) << endl;
	cout << "判断s1和s2的大小关系:";
	if (strcompare(s1, s2)==0)
	cout<< "s"<<"1"<<"="<<"s"<<"2" << endl;
	else if (strcompare(s1, s2) < 0)
	cout << "s" << "1" << "<" << "s" << "2" << endl;
	else if (strcompare(s1, s2) > 0)
		cout << "s" << "1" << ">" << "s" << "2" << endl;
	concat(T, s1, s2);
	cout << "将s1与s2连接成新的串T:";
	shuchu(T);
	cout << endl;
	cout << "输入m,n,用来查找串T中第m个字符开始,长度为n的子串sub" << endl;
	cin >> m >> n;
	cout << "输出子串sub:";
	substring(sub, T, m, n);
	cout << endl;
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值