习题5.13:编写一程序,将两个字符串连接起来,结果取代第一个字符串。(1)用字符数组,不用strcat函数(即自己写一个具有strcat函数功能的函数);

个人答案:

(一)

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hellenionia

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值