串的相关操作

来源:互联网 发布:python生成随机数 编辑:程序博客网 时间:2024/06/08 18:59
/*串的堆分配*/#include<iostream>using namespace std ;typedef struct Hstring{char *ch ;int lenght ;}Hstring ;/*初始化串*/void Init(Hstring &s){s.ch = (char * ) malloc(sizeof(char)) ;if(!s.ch){cout<<"分配内存失败"<<endl;return ;}s.ch = NULL;s.lenght = 0 ;}/*生成一个其值等于a[]的数组*/void StrAssign (Hstring &s , char a[]){if(s.ch) free(s.ch); //释放原来的空间int i ;char *c;for( i = 0, c = a  ; *c ; c ++ ) i ++; //求字符串a的长度if(!i){s.ch = NULL ; s.lenght = 0 ;}else{s.ch = (char *)malloc(sizeof(char));if(!s.ch){cout<<"分配内存失败"<<endl ;return ;}for( int j = 0 ; j < i ; j ++)s.ch[j] = a[j] ;s.lenght = i ;}return ;}/*输出数据*/void outprint(char e ){cout<<e ;}/*遍历整个串*/void TraString(Hstring  s ){if(!s.ch){cout << "空串"<<endl;return ;}for( int i = 0 ; i < s.lenght ; i ++)outprint(s.ch[i]);return ;}int main(void){Hstring s ;Init(s) ;/*创建字串*/cout<<"创建字串:"<<endl;char a[102] ;gets(a);StrAssign(s , a);TraString(s) ;cout<<endl;cout<<"字符串的长度为:"<<s.lenght <<endl;return 0;}

原创粉丝点击