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;
}
结果为: