Reverse string | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Reverse string

Hi. I'm trying to solve the reverse string challenge with using a for loop but gotta problem. The result this code outputs is reversed string only to the halfway, after which the text is normal, not reversed. import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String text = scanner.nextLine(); char[] arr = text.toCharArray(); //your code goes here for(int i=arr.length-1;i>=0;i--) { arr[i] = arr[arr.length-1-i]; } System.out.println(arr); } }

2nd Nov 2021, 8:00 AM
Cynt4
Cynt4 - avatar
1 Answer
+ 3
It's because you are storing the new value in the same old character array. After half of the string is done, the second half now will be just the first half reversed. To solve this, store the reversed string in a new array and copy that new array to your existing array after reversing
2nd Nov 2021, 8:15 AM
Rishi
Rishi - avatar