Learn-dsa..in 30 days!



























CC-1 : Swap Strings without new variable.

Description:

Given two input Strings variables, swap the two variables without using a new variable. String APIs may be used to solve this challenge.

Test cases and expected outputs:

Input Parameters Expected outputs
String str1="Hi";
String str2="There";
String str1="There";
String str2="Hi";
str1="A";
str2="B";
str1="B";
str2="A";

Pseudocode:

The java method should accept following input parameters: str1 (String), str2(String).
Append str1 and str2 using + operator, and set this appended string back to str1. Now str1 contains both str1 and str2.
Extract substring from index 0 to str1.length() from str1 and set it in str2. Now value of input str1 has been swapped to str2.
Extract substring from index str1.length() to end of String and set it to str1. Now value of input str2 has been swapped to str1.
Return swapped str1 and str2 from the program.

Code:

public String[] stringSwapWithoutNewVariable(String str1, String str2) {
	int str1Len=str1.length();
	str1=str1+str2;
	str2=str1.substring(0, str1Len);
	str1=str1.substring(str1Len);
	String retStr[] = {str1, str2};
	return retStr;
}

Click here to download and run code and test cases !