Learn-dsa..in 30 days!



























CC-7 : Reverse the characters of the input String.

Description:

Given input String str, reverse its characters and return the reversed string.

Test cases and expected outputs:

Input Parameters Expected outputs
str1="Reverse" esreveR
str1="Java is the best!"; !tseb eht si avaJ

Pseudocode:

The java method should accept following input parameters: str (String).
Initialize integer variable left to 0. Initialize integer variable right to str.length()-1.
Extract the characters from str into char array names chars.
Initialize char variable temp to false. We will use temp to swap characters while reversing the characters of str.
Iterate through chars using while loop while left < right:
Swap characters at chars[left] and chars[right].
Increment left by 1.
Decrement right by 1.
After above loop has completed, chars contains the characters of str in reverse order. Create a String from chars and return the newly created String with reversed characters.

Code:

public String stringReverse(String str) {
	int left=0; int right=str.length()-1;
	char[] chars=str.toCharArray();
	char temp;
	while (left < right) {
		temp=chars[left];
		chars[left]=chars[right];
		chars[right]=temp;
		left++;
		right--;		
	}
	return new String(chars);
}

Click here to download and run code and test cases !