Reverse String Project | Sololearn: Learn to code for FREE!

+4

Reverse String Project

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 char[] result = new char[arr.length]; //store the result in reverse order into the result char[] for(int i=0; i<arr.length; i++) { result[i] = arr[arr.length - i - 1]; } System.out.println(new String(result)); } } Here I will check all testcases successfully

1/13/2021 8:50:53 AM

AYYAPARAJA K

8 Answers

New Answer

+4

Why do people insist on doing things the hard way? Create a StringBuilder instance from your text string then reverse it... StringBuilder sb = new StringBuilder(text); sb.reverse(); System.out.println(sb); https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/StringBuilder.html

+3

Using for-each for simplicity. 4 lines of code added. https://code.sololearn.com/cig6PA96rplT/?ref=app Your original code has splitted the String into an Char[] array. For-each loop loops through the Char[] array, one Char (i) at a time, from left-to-right order. String rev is the temporary result. "rev = i + rev" means you are adding the i to the front, reversing the String.

+2

K. Ayyaparaja Your program is looking correct. I don't think there would be any issue to pass all test cases.

+2

Martin Taylor The post is a coding question in SoloLearn, under Java, Arrays, after Module 3 Quiz (accessible only on mobile). The existing codes have already split into char[] to demonstrate the understanding of Arrays. One, in any queries, we should not be modifying the pre-existing codes. Two, for this case, we should not code using StringBuilder as that defeats the overall purpose of the Arrays lesson.

+2

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-1;i>=0;i--) { System.out.println(arr[i]); }// Just we start printing from back side } }

+1

+1

OK. Thank you

0

K. Ayyaparaja This is your problem?