最近在复习数据结构,顺便看看大一的时候写的代码,看完之后比当初有了更加深刻的体会。
希望这些能提供给初学者一些参考。
//串的順序存儲結構
#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;
}