Write a program that concatenates two strings and replaces the first string with the result. (three methods)

Use a character array instead of the strcat function (that is, write a program to achieve it yourself);

#include <iostream>
using namespace std;
int main()
{
    char a[80] = { 0 }, b[80], c[80] = { 0 };
    int i, j;
    cout << "输入一字符串" << endl;
    gets_s(a);
    cout << "再输入另一字符串" << endl;
    gets_s(b);
    for (i = 0;i < 80, a[i] != '\0';i++)
        c[i] = a[i];
    c[i] = ' ';
    for (j = 0;j < 80, b[j] != '\0';j++)
        c[i + 1 + j] = b[j];
    for (i = 0;i < 80, c[i] != '\0';i++)
        a[i] = c[i];
    a[i] = 0;
    cout<<"合成为:";
    for (i = 0;i < 80, a[i] != '\0';i++)
        cout << a[i];
    cout << endl;
}

② Implemented with the strcat function in the standard library ;

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
	char a[40], b[40];
	cout << "输入一字符串" << endl;
	gets_s(a);
	cout << "再输入另一字符串" << endl;
	gets_s(b);
	strcat_s(a, b);
	cout <<"连接之后为:" << a << endl;
}

③Use the string method to define a string variable.

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
	string a, b;
	cout << "输入一字符串" << endl;
	cin >> a;
	cout << "再输入另一字符串" << endl;
	cin >> b;
	a = a + b;
	cout << "连接之后为:" << a << endl;
}

Guess you like

Origin blog.csdn.net/weixin_74371035/article/details/127872149