
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ Program to Concatenate Two Strings
A string is a one dimensional character array that is terminated by a null character. Concatenation of two strings is the joining of them to form a new string. For example.
String 1: Mangoes are String 2: tasty Concatenation of 2 strings: Mangoes are tasty
A program to concatenate two strings is given as follows.
Example
#include <iostream> using namespace std; int main() { char str1[100] = "Hi..."; char str2[100] = "How are you"; int i,j; cout<<"String 1: "<<str1<<endl; cout<<"String 2: "<<str2<<endl; for(i = 0; str1[i] != '\0'; ++i); j=0; while(str2[j] != '\0') { str1[i] = str2[j]; i++; j++; } str1[i] = '\0'; cout<<"String after concatenation: "<<str1; return 0; }
Output
String 1: Hi... String 2: How are you String after concatenation: Hi...How are you
In the above program, there are two strings str1 and str2. A for loop is used to reach the end of str1. At the end of the for loop, i contains the index of the null value in the str1. The following code snippet demonstrates this.
for(i = 0; str1[i] != '\0'; ++i);
A while loop is used to transfer the value of str2 to str1. Variable j starts from 0 and copies the character in str2 into str1 at the position pointed by i. This loop runs till value of str2[j] is not null. This is demonstrated as follows.
j=0; while(str2[j] != '\0') { str1[i] = str2[j]; i++; j++; }
After the strings are concatenated in str1, null is added to the end. Then the concatenated string is displayed. The code snippet for this is as follows −
str1[i] = '\0'; cout<<"String after concatenation: "<<str1;
- Related Articles
- How to concatenate two strings using Java?
- How to concatenate two strings in C#?
- How to concatenate two strings in Python?
- How to concatenate two strings in Golang?
- Python program to concatenate Strings around K
- C++ program to concatenate strings in reverse order
- How can we concatenate two strings using jQuery?
- Java Program to Concatenate Two Arrays
- Build complete path in Linux by concatenate two strings?
- How to concatenate strings in R?
- Concatenate strings in Arduino
- Python Program to Concatenate Two Dictionaries Into One
- Concatenate strings from two fields into a third field in MongoDB?
- How to concatenate several strings in JavaScript?
- Different ways to concatenate Strings in Java
