编写⼀程序,将两个字符串连接起来的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;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论