/*
*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;
}
运行结果:
知识点总结:
采用存储串实现字符的重新排序