编写一程序,将两个字符串连接起来的3种方法

1.用字符数组和自己书写的函数实现

自己写一个具有strcat函数功能的函数


实现代码如下:

#include<iostream>
using namespace std;
int main(){
	char a[100],b[50];
	void Strcat(char a[],char b[]);
	cout<<"please input first string:"<<endl;
	cin>>a;
	cout<<"please input second string:"<<endl;
	cin>>b;
	Strcat(a,b);
	cout<<"The new string: "<<a;
	cout<<endl;
	return 0;	
}
void Strcat(char a[],char b[]){
	int i,j;
	for(i=0;a[i]!='\0';i++);
	cout<<"Length of first string:"<<i<<endl;
	for(j=0;b[j]!='\0';j++,i++){
		a[i]=b[j];
	}
	cout<<"Length of second string:"<<j<<endl;
}


2.用标准库中的strcat函数

使用strlen()函数求数组的大小,strcat()函数用来连接字符串

实现代码如下:
#include<iostream>
#include<string>
using namespace std;
int main(){
	char a[100],b[50];
	cout<<"please input first string:"<<endl;
	cin>>a;
	cout<<"please input second string:"<<endl;
	cin>>b;
	cout<<"Length of first string :"<<strlen(a)<<endl;
	cout<<"Length of first string :"<<strlen(b)<<endl;	
	cout<<"The new string: "<<strcat(a,b);
	cout<<endl;
	return 0;	
}


3.用string方法定义字符串变量

#include<iostream>
#include<string>
using namespace std;
int main(){
	string a,b;
	cout<<"please input first string:"<<endl;
	cin>>a;
	cout<<"please input second string:"<<endl;
	cin>>b;
	cout<<"New string :"<<(a+b)<<endl;
	return 0;	
}


  • 8
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值