Swapping two string using swap() function in C++ || string manipulation in c++ || C++


In this, we are going see a program on string manipulation using swap() function in C++ Programming Language.



The Code given below can be used in TURBO C++ Compilers: -

#include <iostream.h>
#include <string.h>
#include <conio.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();
}

//........Coded by YASH ALAPURIA

The Code given below can be used in gcc/g++ Compilers: -

#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;

int main()
{
    system("cls");
    string str1 = "Windows 10";
    string str2 = "Windows 11";

    cout << "Before swapping:-\n";
    cout << "str1 = " << str1 << "\nstr2 = " << str2;

    str1.swap(str2);

    cout << "\n\nAfter swapping:-\n";
    cout << "str1 = " << str1 << "\nstr2 = " << str2;

    return 0;
}

//........Coded by YASH ALAPURIA

#ENJOY CODING

Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post