串的基本操作

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

}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值