on Leave a Comment

C++ Program to Concatenate Two Strings

In C++, we can manipulate two types of strings C-style string and string object of string class.

TOPICS:

(1) Concatenate C-Style Strings

(2) Concatenate String Objects of String Class

C++ Program to Concatenate C-Style Strings

Example 1:

#include<iostream>
using namespace std;
int main()
{
    char str1[50], str2[50], str3[100];
    int i,j;
    cout<<"Enter first string: ";
    cin.getline(str1,50);
    cout<<"\nEnter second string: ";
    cin.getline(str2,50);
    for(i=0;str1[i]!='\0';++i)
        str3[i]=str1[i];
    for(j=0;str2[j]!='\0';++j)
        str3[i+j]=str2[j];
    str3[i+j]='\0';
    cout<<"\nConcatenated string is "<<str3;
    return 0;
}

OUTPUT:

Enter first string: C++

Enter second string: Programming

Concatenated string is C++Programming

Example 2:

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    char str1[50], str2[50];
    cout<<"Enter First String: ";
    cin.getline(str1, 50);
    cout<<"\nEnter Second String: ";
    cin.getline(str2, 50);
    strcat(str1, str2);
    cout<<"\nConcatenated String is "<<str1;
    return 0;
}

OUTPUT:

Enter First String: C++

Enter Second String: Programming

Concatenated String is C++Programming

C++ Program to Concatenate String Objects of String Class

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    string str1, str2;
    cout<<"Enter First String: ";
    getline(cin, str1);
    cout<<"\nEnter Second String: ";
    getline(cin, str2);
    cout<<"\nConcatenated String is "<<str1+str2;
    return 0;
}

OUTPUT:

Enter First String: C++

Enter Second String: Programming

Concatenated String is C++Programming


0 comments:

Post a Comment