C++ Program to Swap two Strings

Google Advertisements

Prev Tutorial Next Tutorial

Swap Two Strings Program in C++

To swap two strings in C++, We need to take two string from user side and store both the string in variables say str1 (string 1) and str2 (string 2).
To swap two strings in C++ Program we need strcpy() function. Here we receive two string from user side and swap these two strings.

To understand below example, you have must knowledge of following C++ programming topics; String in C++ and Array in C++.

C++ Program to Swap Two Strings using Third Variable

#include<iostream.h>
#include<conio.h>
#include<string.h>

void main()
{
    clrscr();
    char str1[30],str2[30],temp[30];
    cout<<"Enter String String 1: ";
    cin>>str1;
    cout<<"Enter String String 2: ";
    cin>>str2;
    strcpy(temp,str1);
    strcpy(str1,str2);
    strcpy(str2,temp);
    cout<<"After Swapping  Strings are: "<<endl;
    cout<<"String 1: "<<str1;
    cout<<endl<<"String 2: "<<str2;
    getch();
}

Output

Enter String String 1: Hello
Enter String String 2: Coder
After Swapping  Strings are: 
String 1: Coder
String 2: Hello
c++ program to swap two strings

Swap Two Strings in C++

C++ Program to Swap Two Strings

#include<iostream.h>
#include<conio.h>
#include<string.h>

void main()
{   int i;
    char str1[30],str2[30],temp[30];
    clrscr();
    cout<<"Enter String String 1 : ";
    cin>>str1;
    cout<<"Enter String String 2 : ";
    cin>>str2;
    for(i=0;(temp[i]=str1[i])!=0;i++);
    for(i=0;(str1[i]=str2[i])!=0;i++);
    for(i=0;(str2[i]=temp[i])!=0;i++);
    cout<<"After Swapping Strings Are: "<<endl;
    cout<<"String 1 : "<<str1;
    cout<<endl<<"String 2 : "<<str2;
    getch();
}

Output

Enter String String 1: Hitesh
Enter String String 2: Kumar
After Swapping  Strings are: 
String 1: Kumar
String 2: Hitesh
c++ program to swap two strings
Prev Tutorial Next Tutorial

Google Advertisements

Buy This Ad Space @$50 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 8076671483

Pure VPN Privide Lowest Price VPN Just @ $1.65. Per Month with Non Detected IP Lowest Price Non Detected IP VPN

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

Cloud computing is the on demand availability of computer system resources, especially data storage and computing power, without direct active management by the user. Cloud Computing Tutorial

College Projects Related to Java, AWT, C Projects for College, C++ Projects for College, Android Projects. Download Java C C++ Projects

Download Projects

Adsense Advertisements


Buy This ads Space 8076671483

Buy This Ad Space @$120 per Month, Ad Size 300X600 Contact on: hitesh.xc@gmail.com or 8076671483 Try this Keyword C++ Programs