再回首,数据结构——字符串与数组的常见操作(顺序存储)

       最近在复习数据结构,顺便看看大一的时候写的代码,看完之后比当初有了更加深刻的体会。

 

      希望这些能提供给初学者一些参考。


//串的順序存儲結構
#define MaxSize 字符串可能達到的最大長度
typedef struct
{
	char ch[MaxSize];
	int StrLength;
}SeqString;

//賦值運算 Assign
void Assign(SeqString *s, char t[])
{
	for (i = 0; t[i] != '\0'; i++)
		s->ch[i] = t[i];
	s->ch[i] = t[i];
	s->StrLength = i;
}

//求串的長度
int Length(SeqString s)
{	
	return s.StrLength;
}

//判斷2個字符串是否相等
int Equal(SeqString s1, SeqString s2)
{
	if(s1.StrLength != s2.StrLength)
		return 0;
	for(i = 0; s1.char[i] != '\0' && s2.char[i] != '\0'; i++)
		if (s1.char[i] != s2.char[i])
			return 0;
	return  1;
}

//串值的連接 Concat
SeqString Concat(SeqString s1, SeqString s2)
{
	for (i = 0; i < s2.StrLength; i++)
		s1.char[s1.StrLength+i] = s2.char[i];
	s1.char[StrLength+i] = '\0';
	s1.StrLength += s2.StrLength;
}

//求子串,Substr(s, i, len).求 s 中從第i(0 <= i <= s.StrLength-1)個位置
//起,長度為length 的子串
SeqString Substr(SeqString s, int i, int len)
{
	if (i < 0 || len < 0 || i+len-1 >= s.StrLength)
	{
		t.ch[0] = '\0';
		t.StrLength = 0;
		return (t);
	}
	for (k = i ; k <= i+len; k++)
		t.ch[k-i] = s.ch[k];
	t.ch[len] = '\0';
	t.StrLength = len;
	return (t);
}

//插入子串,Insert(s,i,t)
void Insert(SeqString *s, int i, SeqString t)
{
	if (i < 0 || i > s.StrLength)
		return;
	for (k = s->StrLength-1; k >= i; k--)
		s->ch[k+t.StrLength] = s->ch[k];
	for (k = i; k < i+t.StrLength; k++)
		s->ch[k] = t.ch[k-i];
	s->ch[s->StrLength+t.StrLength] = '\0';
	s->StrLength = s->StrLength+t.StrLength;
}

//刪除子串 Delete(s,i,len)
void Delete(SeqString *s, int i, int len)
{
	if (i < 0 || i+len-1 >= s->StrLength)
		return;	
	for (k = i+len; k < s->StrLength; k++)
		s->ch[k-len] = s->ch[k];
	s->ch[s->StrLength-len] = '\0';
	s->StrLength = s->StrLength-len;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值