数据结构与算法中串的顺序表实现
#include<stdlib.h>
#include<stdio.h>
typedef struct {
char *ch;
int length;
}heapstring;
void Str_Assign(heapstring *s){
s->ch=(char*)malloc(100*sizeof(char));
printf("\n请输入你串的内容:\n");
gets(s->ch);
}
void PrintString(heapstring *s){
int i=0;
if(!s->ch) printf("\n串是空的!");
else{
printf("\n串的内容是:");
while(s->ch[i]!='\0'){
printf("%c",s->ch[i]);
i++;
}
printf("\t串的长度是%d.",s->length);
printf(" =====输出结束.");
}
}
int MenuShow(){
int e;
printf("\n请你选择:1-串1输出 2-串2输出 3-串比较 4-串复制 5-串连接 6-求子串(exit for 0):");
scanf("%d",&e);
return e;
}
void StrCopy(heapstring *s0,heapstring *t){
int i=0;
if(!(s0->ch=(char*)malloc(100*sizeof(char)))){
printf("\n容量满了!");
exit(0);
}
s0->length =t->length;
while (i<t->length)
s0->ch[i] =t->ch[i++];
s0->ch[i]='\0';
}
int StrCompare(heapstring *s1,heapstring *s2){
int i;
if (!s1->length||!s2->length) printf("\n串是空的!");
else{
for(i=0;i<s1->length&&i<s2->length;++i)
if (s1->ch[i]!=s2->ch[i])
return (s1->ch[i]-s2->ch[i]);
return (s1->length-s2->length);
}
}
void StrConcat(heapstring *s0,heapstring *s1,heapstring *s2){
int i,j;
if(!(s0->ch=(char*)malloc(s0->length*sizeof(char)))){
printf("\n容量满了!");
exit(0);
}else{
for(i=0;s1->ch[i]!='\0';i++)
s0->ch[i]=s1->ch[i];
for(j=0;s2->ch[j]!='\0';j++)
s0->ch[i+j]=s2->ch[j];
s0->ch[i+j]='\0';
}
}
int StrLen(heapstring *s){
int len=0;
while(s->ch[len]!='\0')
len++;
return len;
}
void SubStr(heapstring *s,int pos,int len){
heapstring sub;
int i;
if(pos<1||pos>s->length||len<0||len>s->length-pos+1)
printf("error!");
else {
if (!len){
sub.ch=NULL;
sub.length=0;
}
else {
sub.ch=(char*)malloc(len*sizeof(char));
for(i=0;i<len;i++)
sub.ch[i]=s->ch[pos-1+i];
sub.ch[i]='\0';
sub.length=len;
}
PrintString(&sub);
}
}
main(){
int e,result,k;
int pos,len;
heapstring s1,s2,s0,s3;
Str_Assign(&s1);
s1.length=StrLen(&s1);
Str_Assign(&s2);
s2.length=StrLen(&s2);
e=MenuShow();
while(e!=0){
switch (e){
case 1:
PrintString(&s1);
break;
case 2:
PrintString(&s2);
break;
case 3:
result=StrCompare(&s1,&s2);
if (result) printf("\n串不相等");
else printf("\n串相等");
break;
case 4:
StrCopy(&s0,&s1);
printf("\n串的复制结果是:");
PrintString(&s0);
break;
case 5:
s0.length=s1.length+s2.length;
StrConcat(&s0,&s1,&s2);
PrintString(&s0);
break;
case 6:
printf("\n请输入子串的起始位置和长度:");
scanf("%d%d",&pos,&len);
SubStr(&s1,pos,len);
break;
default:printf("\n输入内容错误!");
}
e=MenuShow();
}
}