Methods to Concatenate Strings in C++

String concatenation in C++ programming language: In this article, we are going to learn different ways to concatenate the strings.
Submitted by Amit Shukla, on August 04, 2017

Concatenation of strings in C++ can be performed using following methods:

  1. Using function strcat() from standard library.
  2. Without using function strcat() from standard library.
  3. Using concatenate operator.

1) Using Standard Library

Here we use a predefined function strcat() from standard string library. We have to use the header file <string.h> to implement this function.

Syntax

char * strcat(char * destination, const char * source)

Example

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
	//string 1
	char src[100]="Include help ";
	//string 2
	char des[100]="is best site";
	
	//Concatenating the string
	strcat(src, des);
	
	//printing 
	cout<<src<<endl;
	
	return 0;
}

Output

Include help is best site.

2) Without using function

In this we concatenate two different string without using concatenation function strcat().

Example

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
	//declare strings 
	char str1[100];
	char str2[100];
	
	//input first string 
	cout<<"Enter first string : "<<endl;
	cin.getline(str1,100);
	
	//input second string 
	cout<<"Enter second string : "<<endl;
	cin.getline(str2,100);
	
	//variable as loop counnters
	int i, j;
	
	//keep first string same 
	for(i=0; str1[i] != '\0'; i++)
	{
		;
	}
	//copy the characters of string 2 in string1
	for(j=0; str2[j] != '\0'; j++,i++)
	{
		str1[i]=str2[j];
	}
	
	//insert NULL
	str1[i]='\0';
	//printing 
	cout<<str1<<endl;
	
	return 0;
}

Output

Enter first string :
IncludeHelp 
Enter second string : 
is best website.
IncludeHelp is best website.

3) Using Concatenate Operator

Here in this section we use the concatenation operator to concatenate two different strings.

Example

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
	//declare string objects
	string str1;
	string str2;
	
	//input first string 
	cout<<"Enter first string : "<<endl;
	cin>>str1;
	
	//input second string 
	cout<<"Enter second string : "<<endl;
	cin>>str2;
	
	//declare another object, that will store the result 
	string str3;
	//concatenate the string using "+"
	str3 = str1 + str2;
	//print the result 
	cout<<str3<<endl;
	
	return 0;
}

Output

Enter first string : 
Include
Enter second string :
Help 
IncludeHelp 




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.