Swapping String in C++


This C++ program demonstrates string manipulation using the copy and swap member functions of the string class.

The program starts by defining two strings str1 and str2. Then, it creates a character array character and uses the copy member function of the string class to copy the first 10 characters of str1 into the character array. The copy function takes three arguments: the destination array, the number of characters to copy, and the starting index of the string to copy from.

Next, the program uses the swap member function of the string class to swap the contents of str1 and str2. The swap function simply exchanges the contents of the two strings. Finally, the program prints the contents of the strings before and after swapping using the cout object.

Source Code

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str1 = "TutorJoe's Educational Centre";
    string str2 = "TutorJoe's Students";
    char character[80];
    str1.copy(character,10,0);
    cout <<"\nThe new copied character array is : ";
    cout <<character<<endl<<endl;
    cout <<"\nThe 1st string before swapping is : ";
    cout <<str1<<endl;
    cout <<"\nThe 2nd string before swapping is : ";
    cout <<str2<<endl;
    str1.swap(str2);
    cout <<"\nThe 1st string after swapping is : ";
    cout <<str1<<endl;
    cout <<"\nThe 2nd string after swapping is : ";
    cout <<str2<<endl;
    return 0;
}
To download raw file Click Here

Output

The new copied character array is : TutorJoe's

The 1st string before swapping is : TutorJoe's Educational Centre

The 2nd string before swapping is : TutorJoe's Students

The 1st string after swapping is : TutorJoe's Students
The 2nd string after swapping is : TutorJoe's Educational Centre


Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples