【串】字符串的定义与基本操作,顺序存储

串是由零个或多个字符组成的有限序列;

子串是串中任意多个连续的字符组成的子序列;

【注】空格串不是空串【注】

关于串的查找,会单独发一篇文章

具体代码如下:

#include<bits/stdc++.h>
using namespace std;
#define Maxsize 100
typedef struct {
	char ch[Maxsize];
	int length;
}Sstring;
void Initstring(Sstring& S) //初始化,这里为处理方便,不使用ch【0】
{
	for (int i = 0; i < Maxsize; i++)
		S.ch[i] = '\0';
	S.length = 0;
}

void Setstring(Sstring& S, string t) //将字符串t复制到S的后面
{
	int len = t.length();
	for (int i = 0; i < len; i++)
		S.ch[S.length + i + 1] = t[i];
	S.length += len;
}

void Insertstring(Sstring& S, char c) //将字符c插入到字符串S的后面空位置
{
	if (S.length == Maxsize - 1)
		cout << "字符串已满!";
	else
	{
		S.length++;
		S.ch[S.length] = c;
	}
}

bool Emptystring(Sstring S) //判空
{
	if (S.length == 0)
		return true;
	return false;
}

void Substring(Sstring S, Sstring& t, int location, int len) //用t返回字符串S中第location个位置起的len个字符
{
	if (location + len - 1 >  S.length)
		cout << "超出字符串范围!" << endl;
	else
	{
		for (int i = 1; i <= len; i++)
			t.ch[i] = S.ch[location + i-1];
		t.length = len;
	}
}

int Comparestring(Sstring S, Sstring T) //比较操作,字符串S和T的大小,本质即按字符串中从头字符起的第一个不同字符的ASCII大小
{
	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;  //若字符串长度不同,则长度较长的大
}

void Conectstring(Sstring& T, Sstring S1, Sstring S2) //用串T返回串S1连接串S2
{
	for (int i = 1; i <= S1.length; i++)
		T.ch[i] = S1.ch[i];
	for (int i = 0; i <= S2.length; i++)
		T.ch[S1.length+i] = S2.ch[i];
	T.length = S1.length + S2.length;
}

int Lengthstring(Sstring S) //串长
{
	return S.length;
}

void Clearstring(Sstring& S) //清空S
{
	Initstring(S);
}

void Printstring(Sstring S) //打印字符串
{
	if (S.length == 0)
		cout << "字符串为空!" << endl;
	else
	{
		for (int i = 1; i <= S.length; i++)
			cout << S.ch[i];
	}
	cout << endl;
}

int main()
{
	Sstring S;
	string t;
	while (cin >> t)
	{
		Initstring(S);
		Setstring(S, t);
		Printstring(S);
		//Insertstring(S, 's');
		//Printstring(S);
		Sstring T;
		Substring(S, T, 2, 3);
		Printstring(T);
		Clearstring(T);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值