个人答案:
(一)
①
#include <iostream>
#include <string>
using namespace std;
void connect(char str1[], char str2[]);
int main()
{
char s1[20], s2[10];
cout << "Please enter string 1: ";
cin >> s1;
cout << "Please enter string 2: ";
cin >> s2;
connect(s1, s2);
cout << s1 << endl;
system("pause");
return 0;
}
void connect(char str1[], char str2[])
{
int i, j;
for (i = 0; str1[i] != '\0'; i++);
for (j = 0; str2[j] != '\0'; str1[i++] = str2[j++]);
str1[i] = '\0';
}
②
#include <iostream>
#include <string> //字符串处理
using namespace std;
int main()
{
char s1[100], s2[50];//[]的100和50为限制字符的长度可以更改,但在运行输入的字符长度不能超过此
int i = 0, j = 0;
cout << "input string1:";
cin >> s1;
cout << "input string2:";
cin >> s2;
while (s1[i] != '\0')//“\0”作用为在s1的元素输出完后结束运行
i++;//确定s1最后一个元素的序号
while (s2[j] != '\0')
s1[i++] = s2[j++];//将s2的元素接在s1后面
s1[i] = '\0';//确定合并后的s1,避免无限循环
cout << "The new string is:" << s1 << endl;
return 0;
}
结果:
(一)其一:
参考答案:
(一)
#include <iostream>
#include <string>
using namespace std;
int main()
{char s1[80],s2[40];
int i=0,j=0;
cout<<"input string1:";
cin>>s1;
cout<<"input string2:";
cin>>s2;
while (s1[i]!='\0')
i++;
while(s2[j]!='\0')
s1[i++]=s2[j++];
s1[i]='\0';
cout<<"The new string is:"<<s1<<endl;
return 0;
}