C++ Program to Swap two Strings

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

Advertisements

Buy This Ad Space @$20 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

Download Projects

Advertisements


Buy Websites 9999595223

Buy Fresh and Payment Receive Media.net Account with Website. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs