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;
}