c/c++串的链式操作


  本篇博客中都是带头结点的串。

1.链式串的定义

  这里的数据域是4个字节,是为了节省空间。

typedef struct StringNode{
	char ch[4];   //按串长分配存储区,ch指向串的基地址
	struct StringNode* next;
} StringNode,*String;

2.初始化

bool StrInit(String &S)
{
	S = (StringNode*)malloc(sizeof(StringNode)); //开辟空间
	if (S == NULL)
		return false;
	S->next = NULL;
	return true;
}

在这里插入图片描述

3.赋值为0

  将数据域中的元素全部初始化为0

bool StrEmpty(String& S)
{
	for (int i = 0; i < 4; ++i)
	{
		S->ch[i] = 0;
	}
	return true;
}

在这里插入图片描述

4.赋值操作

String StrAssign(String &S)
{
	StringNode* s, * r = S; //r为表尾指针
	char e = 0;
	int i = 0;
	cout << "输入你要的字符串:";
	cin >> e;
	s = (StringNode*)malloc(sizeof(StringNode));
	StrEmpty(s);
	while (e != '0')
	{
		s->ch[i] = e;
		i++;
		if (i >= 4)
		{
			r->next = s;
			r = s;
			s = (StringNode*)malloc(sizeof(StringNode));
			StrEmpty(s);
			i = 0;
		}
		cout << "输入你要的字符串:";
		cin >> e;
	}
	r->next = s;
	r = s;
	r->next = NULL;
	return S;
}

5.打印操作

  当指针不指向空的时候,打印数据域。

void PrintString(String S)
{
	S = S->next;
	cout << "字符串:";
	while (S != NULL)
	{
		for (int i = 0; i < 4; i++)
		{
			cout << S->ch[i];
		}
		S = S->next;
	}
}

6.源码

#include<iostream>
using namespace std;
//定义串
typedef struct StringNode{
	char ch[4];   //按串长分配存储区,ch指向串的基地址
	struct StringNode* next;
} StringNode,*String;

//初始化
bool StrInit(String &S)
{
	S = (StringNode*)malloc(sizeof(StringNode)); //开辟空间
	if (S == NULL)
		return false;
	S->next = NULL;
	return true;
}

//赋值为0
bool StrEmpty(String& S)
{
	for (int i = 0; i < 4; ++i)
	{
		S->ch[i] = 0;
	}
	return true;
}

//赋值操作
String StrAssign(String &S)
{
	StringNode* s, * r = S; //r为表尾指针
	char e = 0;
	int i = 0;
	cout << "输入你要的字符串:";
	cin >> e;
	s = (StringNode*)malloc(sizeof(StringNode));
	StrEmpty(s);
	while (e != '0')
	{
		s->ch[i] = e;
		i++;
		if (i >= 4)
		{
			r->next = s;
			r = s;
			s = (StringNode*)malloc(sizeof(StringNode));
			StrEmpty(s);
			i = 0;
		}
		cout << "输入你要的字符串:";
		cin >> e;
	}
	r->next = s;
	r = s;
	r->next = NULL;
	return S;
}

//打印操作
void PrintString(String S)
{
	S = S->next;
	cout << "字符串:";
	while (S != NULL)
	{
		for (int i = 0; i < 4; i++)
		{
			cout << S->ch[i];
		}
		S = S->next;
	}
}

int main()
{
	String S;
	//初始化
	StrInit(S);

	//赋值操作
	StrAssign(S);

	//打印操作
	PrintString(S);
	return 0;
}

在这里插入图片描述

有帮助的话,点一个关注吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

君生我老

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值