您的位置:首页 > 理论基础 > 数据结构算法

(编程训练)再回首,数据结构——字符串操作

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

       希望这些能提供给初学者一些参考。
 
      在VC++6.0下可运行,当初还写了不少注释。
 
【问题描述】
若X和Y是两个顺序存储的串,编写一个算法求出X中第一个不在Y中出现的字符。并且,如果Y串长度为奇数,将该字符替换掉Y串的中间字符,如果Y串长度为偶数,则将该字符插入到Y的中间位置。
【基本要求】
·功能:用串X中第一个不在Y中出现的字符替换Y的中间字符(Y串长度为奇数),或者将其插入到Y的中间位置(Y串长度为偶数)
·输入:串X与串Y
·输出:串Y的中间字符(Y串为奇数)被替换或在中间位置插入字符(Y串长为偶数)后的串值
【测试数据】
输入串X:abcdeuvw,输入串Y:abcdefghij,预期的输出是abcdeufghij。
输入串X:abcdeuvw
, 输入串Y:abcdefghijk,预期的输出是abcde
ufghij。
输入串X:abcdefghij,输入串Y:abcdefghij,预期的输出是abcdefghij。
【模块划分】
①创建串结构Create。
②求出串x中第一个不在Y中出现的字符FirstChr。
③用一字符替换成串(长度为奇数)的中间字符,或将一字符插入到串(长度为偶数的中间位置RepOrIns。
④主函数main,调用Create创建X与Y,调用FirstChr和RepOrIns,输出串y的值。

/*字符串操作*/
#include <stdio.h>
#include <malloc.h>
#define MaxSize 1000

//定义数据结构
typedef struct
{
char ch[MaxSize];
int StrLength;
}SeqString;

//创建字符串
void Creat(SeqString *x)
{
int len=0;
printf("Enter the string: ");
gets(x->ch);
while(x->ch[len]!='\0')
len++;
x->StrLength=len;
}

//求字符串x中第一个不在字符串y中出现的字符
char FirstChar(SeqString x, SeqString y)
{
int i,j,flag;
i=0;
flag=1;
while(x.ch[i]!='\0'&&flag)
{
j=0;
while(y.ch[j]!='\0')
{
if(x.ch[i]!=y.ch[j])
j++;
else
break;
}
if('\0'==y.ch[j])
flag=0;
else
i++;
}
if(0==flag)
return x.ch[i];
else
return '\0';
}
//将字符串x中返回的字符在字符串y中插入或替换
void RepOrIns (SeqString *y, char x)
{
int i;
if('\0'==x)
return;
if(y->StrLength%2)
{
//替换
y->ch[y->StrLength/2]=x;
return;
}
else
{
//插入
for(i=y->StrLength;i>=y->StrLength/2;i--)
y->ch[i+1]=y->ch[i];
y->ch[i+1]=x;
y->StrLength+=1;
}
}
//main函数
int main(void)
{
SeqString *x,*y;
char ch;
int n;
scanf("%d",&n);
getchar();
x=(SeqString*)malloc(sizeof(SeqString));
y=(SeqString*)malloc(sizeof(SeqString));
while(n--)
{
Creat(x);
Creat(y);
ch=FirstChar(*x,*y);
RepOrIns(y,ch);
printf("%s\n",y);
}
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构