Program to swap two string variables without using third or temp variable

Explanation

In this program, we need to swap two strings without using a third variable.

Swapping two strings usually take a temporary third variable. One of the approach to accomplish this is to concatenate given two strings into first string.

Extract string 2 using substring (0, length(string1) - (string2)) i.e. in our case it will be substring(0, (11-4)). It will assign string Good to string 2 which is highlighted by green.

Extract string 1 using substring (length(string2)) i.e. we need to extract string from in length(string2) till end of the string. In our case it will be substring(4). It will assign string morning to string 1 which is highlighted by green.

Algorithm

  1. Define two strings that need to be swapped.
  2. Concatenate both the strings and store it in first string.
  3. Extract the string from indexes 0 to length (string1) - (string2) using substring function and store it in string 2.
  4. Extract the string from index length (string2) till end using substring function and store it in string 1.

Solution

Python

Output:

Strings before swapping: Good morning
Strings after swapping: morning Good

C

Output:

Strings before swapping: Good morning
Strings after swapping: morning Good

JAVA

Output:

Strings before swapping: Good morning
Strings after swapping: morning Good

C#

Output:

Strings before swapping: Good morning
Strings after swapping: morning Good

PHP

Output:

Strings before swapping: Good morning
Strings after swapping: morning Good

Next Topic#




Latest Courses