+ 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); } }
1 Resposta
+ 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