Program to swap two strings

Description

Swap two strings means first string will be second string and second string will be the first string.

C/C++

/* C Program to swap two strings */
//Save it as SwapTwoStrings.c


#include<stdio.h>
int main(){

    char firstString[100], secondString[100], tempString[100];

    printf("Enter first String : ");
    gets(firstString);

    printf("Enter second string : ");
    gets(secondString);

    printf("The string before swap %s and %s",firstString,secondString);

    //copy the value firstString variable into temporary variable
    strcpy(tempString,firstString);

    //copy the value secondString variable into firstString variable
    strcpy(firstString,secondString);

    //copy the value temporary variable into secondString variable
    strcpy(secondString,tempString);

    printf("\nThe string after swap %s and %s",firstString,secondString);

    return 0;
}
Input:
Enter first String : abc
Enter first String : def

Output:
The string before swap abc and def
The string after swap def and abc

Java

/* Java Program to swap two strings */
//Save it as SwapTwoStrings.java

import java.io.*;
import java.util.Scanner;

public class SwapTwoStrings {

    public static void main(String[] args) {

            Scanner scanner = new Scanner(System.in);

        System.out.println("Enter first String : ");
        String firstString = scanner.nextLine();

        System.out.println("Enter second String : ");
        String secondString = scanner.nextLine();

        System.out.println("The string before swap "+firstString+" and "+secondString);

            //Assign the value firstString variable into temporary variable
        String tempString = firstString;

            //Assign the value secondString variable into firstString variable
        firstString = secondString;

            //Assign the value temporary variable into secondString variable
        secondString = tempString;

        System.out.println("The string after swap "+firstString+" and "+secondString);
    }
}
Input:
Enter first String : 
abc
Enter first String : 
def

Output:
The string before swap abc and def
The string after swap def and abc

Related programs

1) Program to Swap Two Numbers
2) Program to calculate Gross Salary
3) Program to display multiplication table of a number
4) Program to Display Fibonacci Series using Recursion
5) Program to find sum of first and last digit of a number
6) Program to find HCF using Recursion
7) Program to find largest and smallest digit in a Number
8) Program to find largest and smallest character in a String
9) Program to calculate power of a number using recursion
10) Program To Check Armstrong Number
Share Me

Leave a Reply