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

Reverse a String

Hello, I completed the Challenge Rerverse a String in Java, but Im not sure if this is the way of clean coding. It felts wrong :D If i try to do the decrement into the head of the Loop i will get an index out of bounds Exception. 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(); for(int i = arr.length; i>0;){ System.out.print(arr[--i]); } } }

25th Jul 2021, 11:26 AM
Pascal
11 Answers
+ 5
Not gonna comment on the "clean coding" theory. Just about one thing, this code outputs each character of the String in reverse order, not creating a new String which contains the reversed content of the original String. If the task asked to output characters of a String in reverse order, this is correct, I guess.
25th Jul 2021, 12:04 PM
Ipang
+ 5
Pascal Yes you will get exception because array index start from 0 so if there is string "abc" and you do arr[3] then you will get exception because of index 0 1 2 but you are accessing 3rd. So to avoid this problem you can do this: for (int i = arr.length - 1; i >= 0; i--) { System.out.print(arr[i]); }
25th Jul 2021, 12:33 PM
A͢J
A͢J - avatar
+ 4
If you need to preserve the reversed string this works nicely and utilizes the loop efficiently... char [] array = origString.toCharArray(); for(int i=0; i<array.length/2; i++) { char character = array[i]; array[i] = array[array.length -i -1]; array[array.length -i -1] = character; } String reversed = new String(array);
25th Jul 2021, 2:06 PM
Paul K Sadler
Paul K Sadler - avatar
+ 3
Thanks for the feedback guys, right it was suppose to use an array. The give me a string an converted it to an char array. I should reverse that array in an Loop and put it out. System.out.println(new StringBuilder(string).reverse().toString()); I know i could reverse a string with an Stringbuilder but i was suppose to use an for loop and an array Thank you very much. greets Pascal
25th Jul 2021, 8:28 PM
Pascal
+ 3
Pascal For solutions suggesting the standard library, that itself defeat the purpose of the Challenge in the first place. And for the solution you pasted above, it isn't elegant and doesn't reverse a String, even though it iterates and prints each character from the back. For the solutions suggested creating new String within each iteration of the loop, that's also a very expensive operation and very bad. The best solution in this thread is that of Paul K Sadler but he made it less readable, also using new operator to create a String A modified and readable version of it is String reverse(String str){ char[] els = str.toCharArray(); for(int i = 0; i < els.length / 2; i++){ char temp = els[i]; els[i] = els[(els.length - 1) - i ]; els[(els.length - 1) - i] = temp; } return String.valueOf(els); } This is the most elegant and efficient solution I can think of atm You can test it here: https://code.sololearn.com/c2J1hYTdtaXG/?ref=app
26th Jul 2021, 7:59 PM
maleeqB
maleeqB - avatar
+ 3
maleeqB Since String.valueOf() returns a new String() internally, isn't it identical to Paul K Sadler's version? (Except refactored into a method). Anyway, Kent Beck and Bob Martin (and the "clean code" gurus) would probably argue that reversal and swapping should be split into separate methods: https://code.sololearn.com/ca1A24a24a22 ... for elegance, purity, and "readability".
26th Jul 2021, 10:48 PM
Mike A
Mike A - avatar
+ 2
Help me Please! Explain how this works? I didn't understand anything from the course.
9th Feb 2022, 5:01 AM
Aleksandr Trofimov
Aleksandr Trofimov - avatar
+ 1
maleeqB Since String.valueOf() returns a new String() internally, isn't it identical to Paul K Sadler's version? (Except refactored into a method). Anyway, Kent Beck and Bob Martin (and the "clean code" gurus) would probably argue that reversal and swapping should be split into separate methods: https://code.sololearn.com/ca1A24a24a22 ... for elegance, purity, and "readability". Why are you dividing length by 2? swap(arr, i, arr.length - i - 1); And this part, why arr.length - i - 1
27th Jul 2021, 11:03 AM
Pascal
+ 1
Pascal The length is divided by two for loop termination, because by working from the two ends swapping characters inwatds you only need 1/2 the length loop iterations to swap characters and meet in the middle.
27th Jul 2021, 2:19 PM
Paul K Sadler
Paul K Sadler - avatar
0
Easiest way: You can use StringBuffer/StringBuilder. Smarter way: String reverse = ""; for (int i = text.length() - 1; i >= 0; i--) reverse += text.charAt(i); //there you go :)
25th Jul 2021, 3:08 PM
Yahel
Yahel - avatar
0
Aleksandr Trofimov That's OK, do the entire course/lesson again. Pascal notice this thread and the discussion of Big O with Morpheus. It was very informative, caused me to refractor the code taking into account time complexity. https://code.sololearn.com/WF3w8IDIoRGg/?ref=app
10th Feb 2022, 3:37 AM
Paul K Sadler
Paul K Sadler - avatar