/* * Copyright (c) 2015, 烟台大学计算机与控制工程学院 * All rights reserved. * 文件名称: SqString.cpp,main.cpp,SqString.h * 作者:巩凯强 * 完成日期:2015年10月20日 * 版本号:codeblocks * * 问题描述: 采用顺序存储方式存储串,实现下列算法并测试: * 输入描述:无 * 程序输出:见下面的运行结果 */ #ifndef SQSTRING_H_INCLUDED #define SQSTRING_H_INCLUDED #include <stdio.h> #include <malloc.h> #define MaxSize 100 //最多的字符个数 typedef struct { char data[MaxSize]; //定义可容纳MaxSize个字符的空间 int length; //标记当前实际串长 } SqString; void StrAssign(SqString &s,char cstr[]); //字符串常量cstr赋给串s int StrLength(SqString s); //求串长 void DispStr(SqString s); //输出串 void Trans(SqString &s, char c1, char c2); void Invert(SqString &s); void DellChar(SqString &s, char c); SqString CommChar(SqString s1,SqString s2); #endif // SQSTRING_H_INCLUDED
#include "SqString.h" void StrAssign(SqString &s,char cstr[]) { int i; for(i=0;cstr[i]!='\0';i++) { s.data[i]=cstr[i]; } s.length=i; } int StrLength(SqString s) { return s.length; } void DispStr(SqString s) { int i; if(s.length>0) { for(i=0;i<s.length;i++) printf("%c",s.data[i]); printf("\n"); } } 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 i,k=0; for(i=0;i<s.length;i++) { if(s.data[i]==c) { continue; } else { s.data[k]=s.data[i]; k++; } } s.length=k; } SqString CommChar(SqString s1,SqString s2) { int i,j,k=0; for(i=0;i<s1.length;i++) { for(j=0;j<s2.length;j++) if(s1.data[i]==s2.data[j]) { break; } if(j<s2.length) { s1.data[k]=s1.data[i]; k++; } } s1.length=k; return s1; }
#include "SqString.h" int main() { SqString s1, s2, 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); StrAssign(s1, "message"); StrAssign(s2, "agent"); s = CommChar(s1, s2); DispStr(s); return 0; }
运行结果:
知识点总结:
本程序主要是对顺序串的简单应用。
学习心得:
在删字符的那个程序以及得到公共串的那个程序和老师的略有不同,也可以参考一下