×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

Methods to Concatenate Strings in C++

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.

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 <string.h>

#include <iostream>
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.

Without using function

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

Example

#include <string.h>

#include <iostream>
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.

Using Concatenate Operator

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

Example

#include <string.h>
#include <iostream>
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.