C++ Strings : append()

String Append

A string in C++ is actually an object, which contain functions that can perform certain operations on strings. For example, you can also concatenate strings with the append() function.

Example:1

string n=”Hello”;
n.append(“World”);
cout<<“String is “<<n<<endl;

Output:
HelloWorld

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string n="Hello";
	n.append("World");
	cout<<"String is "<<n<<endl;
	return(0);
}

Example:2

string n1,n2;
n1=”Hello”;
n2=”World”;
n1.append(n2);
cout<<“n1 “<<n1<<endl;
cout<<“n2 “<<n2<<endl;

Output:
n1 HelloWorld
n2 World

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string n1,n2;
	n1="Hello";
	n2="World";
	n1.append(n2);
	cout<<"n1 "<<n1<<endl;
	cout<<"n2 "<<n2<<endl;
	return(0);
}

Example:3

string n1,n2;
n1=”Hello”;
n2=”World”;
string n3=n1.append(n2);
cout<<“n1 “<<n1<<endl;
cout<<“n2 “<<n2<<endl;
cout<<“n3 “<<n3<<endl;

Output:
n1 HelloWorld
n2 World
n3 HelloWorld

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string n1,n2;
	n1="Hello";
	n2="World";
	string n3=n1.append(n2);
	cout<<"n1 "<<n1<<endl;
	cout<<"n2 "<<n2<<endl;
	cout<<"n3 "<<n3<<endl;
	return(0);
}

Example:4

string n1,n2,n3;
n1=”Hello”;
n2=”World”;
n3.append(n1);
n3.append(” “);
n3.append(n2);
cout<<“n1 “<<n1<<endl;
cout<<“n2 “<<n2<<endl;
cout<<“n3 “<<n3<<endl;

Output:
n1 Hello
n2 World
n3 Hello World

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string n1,n2,n3;
	n1="Hello";
	n2="World";
	n3.append(n1);
	n3.append(" ");
	n3.append(n2);
	cout<<"n1 "<<n1<<endl;
	cout<<"n2 "<<n2<<endl;
	cout<<"n3 "<<n3<<endl;
	return(0);
}

Note:
It is up to you whether you want to use + or append(). The major difference between the two, is that the append() function is much faster. However, for testing and such, it might be easier to just use +.