- /*用动态数组实现串连接操作。从屏幕输入:
- * 串1"Get busy living, "
- * 串2"Or get busy dying."
- * 从屏幕输出:
- * "Get busy living, Or get busy dying."*/
- #include <stdio.h>
- #include <iostream.h>
- #include <stdio.h>
- #include <stdlib.h>
- #define MAXSIZE_S1 100
- #define MAXSIZE_S2 100
- struct HString
- {
- char *ch;
- int length;
- };
- int StrAssign(HString &S,char * chars)
- {
- int i,j;
- char *c;
- if (S.ch) free(S.ch);
- for(i = 0, c = chars; *c; i++, c++);
- if(!i)
- {
- S.ch=NULL;
- S.length=0;
- }
- else
- {
- if(!(S.ch=(char *)malloc(i*sizeof(char))))
- {
- cout<<"OVERFLOW!"<<endl;
- return (0);
- }
- else
- {
- for(j = 0; j <= i; j++)
- S.ch[j] = chars[j];
- S.length = i;
- }
- }
- return(0);
- }
- int Concat(HString &T ,HString S1,HString S2)
- {
- int i;
- if (T.ch) free(T.ch);
- T.length=S1.length+S2.length;
- if(!(T.ch=(char*)malloc((S1.length+S2.length)*sizeof(char))))
- {
- cout<<"overflow"<<endl;
- return 0;
- }
- for(i=0;i<=S1.length;i++)
- {
- T.ch[i]=S1.ch[i];
- }
- for(i=0;i<=S2.length;i++)
- {
- T.ch[S1.length+i]=S2.ch[i];
- }
- T.ch[i+S1.length]=NULL;
- cout<<T.ch<<endl;
- return 0;
- }
- int main()
- {
- HString T,S1,S2;
- char c;
- char char_S1 [MAXSIZE_S1];
- char char_S2 [MAXSIZE_S2];
- T.ch = S1.ch = S2.ch = NULL;
- T.length = S1.length = S2.length = 0;
- cout<<"Enter intput char_S1:"<<endl;
- gets(char_S1);
- cout<<"Enter intput char_S2:"<<endl;
- gets(char_S2);
- StrAssign(S1,char_S1);
- StrAssign(S2,char_S2);
- printf("%s/n%s/n", S1.ch, S2.ch);
- Concat(T,S1,S2);
- return 0;
- }
用动态数组实现串连接操作-作业0402-(串)
最新推荐文章于 2021-02-27 17:57:53 发布
本文介绍了一种使用动态数组来实现字符串连接的方法。通过两个示例字符串“Get busy living,” 和 “Or get busy dying.”,演示了如何创建动态数组、分配内存、复制字符串并进行连接。最终输出连接后的完整字符串。
摘要由CSDN通过智能技术生成