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

Google Advertisment

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

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

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements