C++第五章课后习题13

13.编写一程序,将两个字符串连接起来,结果取代第一个字符串。

  • 用字符数组,不用stract函数(即自己写一个具有stract函数功能的函数);
  • 用标准库中的stract函数;
  • 用string方法定义字符串变量。

代码如下

用字符数组:

#include <iostream>
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';
}

用标准库中的stract函数;

#include<bits/stdc++.h>
using namespace std;
int main()
{
	char str1[30]="People's Republic of ";
	char str2[30]="China";
	cout<<strcat(str1,str2);                //调用strcat函数 
	return 0;
}

用string方法定义字符串变量

#include<bits/stdc++.h>
#include<string> 
using namespace std;
int main()
{
	string str1="People's Republic of ";
	string str2="China";
	cout<<str1+str2; 
	return 0;
}

结果为:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值