字符串的顺序存储和操作
#include <stdio.h>
#include <stdlib.h>
// 4.1字符串是元素类型为字符型的特殊线性表,因此也有顺序存储和链式存储
#define MAX_SIZE 100
typedef struct
{
char str[MAX_SIZE];
int length;
}seqString;
// 1.顺序表的初始化/置空表
void init(seqString *str)
{
str->length = 0;
}
// 2.打印顺序表各结点的值
void display(seqString slt)
{
if(!slt.length)
{
printf("顺序表是空的!\n");
return;
}
for (int i = 0; i < slt.length; i++)
printf("%c ",slt.str[i]);
printf("\n");
}
// 3.在顺序表尾部追加值为x的元素
void append(seqString *str,char x)
{
if(str->length == MAX_SIZE)
{
printf("顺序表是满的,无法追加!\n");
exit(1);
}
str->str[str->length] = x;
str->length++;
}
// 3.将字符t插到s中的第i个字符开始的位置上
void strInsert(seqString *s, int i, seqString *t)
{
if(i < 1 || i > s->length+1)
{
printf("插入的位置非法!");
return;
}
if(t->length+s->length > MAX_SIZE-1)
{
printf("字符串过长!");
return;
}
for (int j = s->length-1;j >= i-1; j--)
s->str[j+t->length] = s->str[j];
for (int m=0; m < t->length; m++,i++)
s->str[i-1] = t->str[m];
s->length += t->length;
t->length = 0;
}
// 4.将串s从第i个字符起删除len个长度的字串
void del(seqString *s, int i, int len)
{
if(len < 1 || len > s->length-i+1)
{
printf("操作非法,无法删除!\n");
return;
}
for (; i < s->length; i++)
{
s->str[i-1] = s->str[i+len-1];
}
s->length -= len;
}
// 5.字符串拼接
void strConcat(seqString *s, seqString *t)
{
if(s->length + t->length > MAX_SIZE)
{
printf("空间不足,无法拼接!\n");
return;
}
for (int i = 0; i < t->length; i++)
{
s->str[s->length++] = t->str[i];
}
}
// 6. 求字串
seqString *substring(seqString s, int i, int len)
{
seqString *p = (seqString*) malloc(sizeof(seqString));
init(p);
if(len < 1 || len > s.length-i+1)
{
printf("获取字串操作非法!\n");
return p;
}
for (int j = 0; j < len; i++)
p->str[j++] = s.str[i-1];
p->length = len;
return p;
}
int main()
{
seqString s,t;
init(&s);
init(&t);
for (int i = 'a'; i < 'f'; ++i)
append(&s,(char)i);
printf("字符串s: ");
display(s);
for (int i = 'A'; i < 'D'; ++i)
append(&t,(char)i);
printf("字符串t: ");
display(t);
printf("把字符串t拼接在s后\n");
strConcat(&s,&t);
printf("字符串s: ");
display(s);
int i = 3;
printf("将字符t插到s中的第%d个字符开始的位置上\n",i);
strInsert(&s,i,&t);
printf("字符串s: ");
display(s);
int len = 3;
printf("将串s从第%d个字符起删除%d个长度的字串\n",i,len);
del(&s,i,len);
printf("字符串s: ");
display(s);
seqString *str = substring(s,i,len);
printf("字符串s从第%d个字符开始长度为%d的字串:\n",i,len);
display(*str);
return 0;
}
评论 (0)