您的位置:首页 > 其它

串的基本操作

2016-04-01 10:35 260 查看
#include<iostream>

#include<string>

using namespace std;

#define TRUE 1;

#define FALSE 0;

#define OK 1;

#define ERROR 0

#define INFEASIBLE -1

#define OVERFLOW -2

typedef struct {
int length;
char *ch;

}Hstring;

int strassign(Hstring&T,char *chars){int i=0;//生成串

while(chars[i]) i++;T.ch=(char*)malloc(i*sizeof(char));

if(!T.ch)exit(OVERFLOW);

for(int j=0;j<i;j++)T.ch[j]=chars[j];T.length=i;

return 0;}

int Strlength(Hstring T){
return T.length;

}

int clearstring(Hstring&L){//清空串
if(L.ch)free(L.ch);
L.ch=0;L.length=0;
return 0;}

int Concat(Hstring &A,Hstring B,Hstring C)//合并两个串

{
A.ch=(char*)malloc((B.length+C.length)*sizeof(char));
if(!A.ch)exit(OVERFLOW);int i=0;for(i;i<B.length;i++)A.ch[i]=B.ch[i];for(int j=0;j<C.length;j++,i++)A.ch[i]=C.ch[j];
/*int i=0;while(B.ch[i]) {A.ch[i]=B.ch[i];i++;}  int j=0;
while(C.ch[j]){A.ch[i+1]=C.ch[j];i++;j++;}*/
A.length=B.length+C.length;
return 0;

}

int Substring(Hstring&T,Hstring S,int pos,int len){//截取部分串
T.ch=(char*)malloc(len*sizeof(char));
T.length=len;
int j;
for(j=0;j<len;j++,pos++){
T.ch[j]=S.ch[pos-1];
}return 0;

}

int printf(Hstring L){//输出串
for(int y=0;y<L.length;y++)
cout<<L.ch[y];

return 0;}
int jiansuo(Hstring&L,Hstring&S){int i=0,j=0;while(i<L.length&&j!=S.length){//检索串
if(L.ch[i]==S.ch[j]){i++;j++;}

else if(L.ch[i]!=S.ch[j]){i=i-j+1;j=0;}
}

if(j==S.length){cout<<"检索成功";}

if(j!=S.length){cout<<"检索失败";}

return 0;}

int main(){
char *i="ABCDEFG";char *u="HJKL";
Hstring A;

strassign(A,i);

printf(A);

cout<<"串的元素个数:"<<Strlength(A)<<endl;

Hstring C;Hstring B;strassign(B,u);

cout<<"串A:";printf(A);cout<<endl;

cout<<"串B:";printf(B);cout<<endl;

Concat(C,B,A);

cout<<"两个串合并 串C:";

printf(C);cout<<endl;

cout<<"返回串从第三个字符开始的长度为5 串D:";

Hstring D;

Substring(D,C,3,5);

printf(D);

cout<<endl<<"开始检索"<<endl;

cout<<"C中检索A...检索结果:";jiansuo(C,A);cout<<endl;

cout<<"C中检索B...检索结果:";jiansuo(C,B);cout<<endl;

cout<<"C中检索D...检索结果:";jiansuo(C,D);cout<<endl;

return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: