串结构练习——字符串连接
Description
给定两个字符串string1和string2,将字符串string2连接在string1的后面,并将连接后的字符串输出。
连接后字符串长度不超过110。
Input
输入包含多组数据,每组测试数据包含两行,第一行代表string1,第二行代表string2。
Output
对于每组输入数据,对应输出连接后的字符串,每组输出占一行。
Sample
Input
123 654 abs sfg
Output
123654 abssfg
Hint
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
4
5 void conat(char t[], char s1[], char s2[])
6 {
7 int i=0, k=0;
8 while(s1[i]!='\0')
9 t[k++]=s1[i++];
10 i=0;
11 while(s2[i]!='\0')
12 t[k++]=s2[i++];
13 t[k]='\0';
14 }
15
16 int main()
17 {
18 char t[111], s1[111], s2[111];
19 while(gets(s1)!=NULL)
20 {
21 gets(s2);
22 conat(t, s1, s2);
23 puts(t);
24 }
25 }
标准格式
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef char status;
typedef struct
{
char *ch; //若是非空串,按串长分配存储区, 否则ch为NULL
int length; //串长度
} String;
status initstring(String &s)//初始化一个串
{
s.ch = (char *)malloc(sizeof(char));
if(!s.ch) exit(0);
s.ch=NULL;
s.length = 0;
return 1;
}
void strassign(String &s, char str[])//为串t赋值
{
if(s.ch)
free(s.ch); //释放t原有空间
int i=0;
while(str[i]!='\0') //求str长度i
i++;
if(!i)
{
s.ch = NULL;
s.length = 0;
}
else
{
s.ch = (char *) malloc ((i+1) * sizeof(char));
if(!s.ch) exit(0);
int j=0;
for(j=0; j<i; j++)
s.ch[j]=str[j];
s.length = i;
}
}
status concat(String &t, String &s1, String &s2)
{
int i, j;
if(t.ch)
free(t.ch);
t.ch = (char *) malloc ((s1.length+s2.length+1) * sizeof(char));
if(!t.ch) exit(0);
for(i=0; i<s1.length; i++)
t.ch[i] = s1.ch[i];
t.length=s1.length+s2.length;
for(i=0; i<s2.length; i++)
t.ch[s1.length+i]=s2.ch[i];
return 1;
}
void printf(String s)
{
int i;
for(i=0; i<s.length; i++)
printf("%c", s.ch[i]);
printf("\n");
}
int main()
{
char str1[111], str2[111];
String s1, s2, t;
while(~scanf("%s", str1))
{
initstring(s1);
initstring(s2);
strassign(s1, str1);
scanf("%s", str2);
strassign(s2, str2);
initstring(t);
concat(t, s1, s2);
printf(t);
}
}
来源:https://www.cnblogs.com/xiaolitongxueyaoshangjin/p/12568811.html