第八周 项目3-顺序串算法(2)

/* 
 *Copyright(c) 2015, 烟台大学计算机学院 
 *All rights reserved. 
 *文件名称:顺序串算法(2).cpp 
 *作    者:周洁 
 *完成日期:2015年 10月26日 
 *版 本 号: 
 * 

 *问题描述:采用顺序存储方式存储串,实现下列算法并测试:

试编写算法,实现将已知字符串所有字符倒过来重新排列。如ABCDEF改为FEDCBA。
void Invert(SqString &s)

 *输入描述:串的输入

 *程序输出:操作后的输出

 */

 

代码:

(1)头文件 s.h

#ifndef SqString_H_INCLUDED
#define SqString_H_INCLUDED

#define MaxSize 100             //最多的字符个数
typedef struct
{   char data[MaxSize];         //定义可容纳MaxSize个字符的空间
    int length;                 //标记当前实际串长
} SqString;

void StrAssign(SqString &s,char cstr[]);    //字符串常量cstr赋给串s
void StrCopy(SqString &s,SqString t);   //串t复制给串s
bool StrEqual(SqString s,SqString t); //判串相等
int StrLength(SqString s);  //求串长
SqString Concat(SqString s,SqString t);  //串连接
SqString SubStr(SqString s,int i,int j); //求子串
SqString InsStr(SqString s1,int i,SqString s2); //串插入
SqString DelStr(SqString s,int i,int j) ;   //串删去
SqString RepStr(SqString s,int i,int j,SqString t);     //串替换
void DispStr(SqString s);   //输出串

#endif // SqString_H_INCLUDED

 

(2)源文件 s.cpp

#include <stdio.h>
#include "s.h"
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 StrAssign(SqString &s,char cstr[]) //s为引用型参数
{   int i;
    for (i=0;cstr[i]!='\0';i++)
        s.data[i]=cstr[i];
    s.length=i;
}


void DispStr(SqString s)
{   int i;
    if (s.length>0)
    {   for (i=0;i<s.length;i++)
            printf("%c",s.data[i]);
        printf("\n");
    }
}


int main()
{
    SqString s;
    StrAssign(s, "abcdefg");
    Invert(s);
    DispStr(s);
    return 0;
}

 

运行结果:

 

知识点总结:

采用存储串实现字符的重新排序

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值