第八周实践项目3 顺序串一些算法操作

sqString.h

#define MaxSize 100             //最多的字符个数
typedef struct
{   char data[MaxSize];         //定义可容纳MaxSize个字符的空间
    int length;                 //标记当前实际串长
} SqString;
void StrAssign(SqString &s,char cstr[]);    //字符串常量cstr赋给串s
SqString DelStr(SqString s,int i,int j) ;   //串删去
void DispStr(SqString s);   //输出串
sqString.cpp

#include <stdio.h>
#include <malloc.h>
#include "SqString.h"
void StrAssign(SqString &s,char cstr[]) //s为引用型参数
{   int i;
    for (i=0;cstr[i]!='\0';i++)
        s.data[i]=cstr[i];
    s.length=i;
}
SqString DelStr(SqString s,int i,int j)
{   int k;
    SqString str;
    str.length=0;
    if (i<=0 || i>s.length || i+j>s.length+1) //参数不正确时返回空串
        return str;
    for (k=0;k<i-1;k++)             //将s.data[0..i-2]复制到str
        str.data[k]=s.data[k];
    for (k=i+j-1;k<s.length;k++)    //将s.data[i+j-1..s.length-1]复制到str
        str.data[k-j]=s.data[k];
    str.length=s.length-j;
    return str;
}
void DispStr(SqString s)
{   int i;
    if (s.length>0)
    {   for (i=0;i<s.length;i++)
            printf("%c",s.data[i]);
        printf("\n");
    }
}
main.cpp

#include <stdio.h>
#include "sqString.h"
void Trans(SqString &s, char c1, char c2)
{
    int i;
    for (i=0; i<s.length; i++)
        if (s.data[i]==c1)
            s.data[i]=c2;
}
void Invert(SqString &s)
{
    int i;
    char temp;
    for (i=0; i<s.length/2; i++)
    {
        temp = s.data[i];
        s.data[i]=s.data[s.length-i-1];
        s.data[s.length-i-1] = temp;
    }
}
void DellChar(SqString &s, char c)
{
    int k=0, i=0;   //k记录值等于c的字符个数
    while(i<s.length)
    {
        if(s.data[i]==c)
            k++;
        else
            s.data[i-k]=s.data[i];
        i++;
    }
    s.length -= k;
}
SqString CommChar(SqString s1,SqString s2)
{
    SqString s3;
    int i,j,k=0;
    for (i=0; i<s1.length; i++)
    {
        for (j=0; j<s2.length; j++)
            if (s2.data[j]==s1.data[i])
                break;
        if (j<s2.length)            //s1.data[i]是公共字符
        {
            s3.data[k]=s1.data[i];
            k++;
        }
    }
    s3.length=k;
    return s3;
}
int main()
{
    SqString s;
    StrAssign(s, "messages");
    Trans(s, 'e', 'a');
    DispStr(s);

    StrAssign(s, "abcdefg");
    Invert(s);
    DispStr(s);

     StrAssign(s, "message");
    DellChar(s, 'e');
    DispStr(s);

      SqString s1, s2 ;
     StrAssign(s1, "message");
    StrAssign(s2, "agent");
    s = CommChar(s1, s2);
    DispStr(s);
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值