Needs Logic explanation java reverse string

180 Views Asked by At

Question of reverse string without using string function I didn't get the inner for loop why s.length()-1 ? why -1 ? its something have to do like multi dimensional arrays?

char ch[]=new char[s.length()];
for(i=0;i < s.length();i++)
    ch[i]=s.charAt(i);
for(i=s.length()-1;i>=0;i--)
    System.out.print(ch[i]);

found this code but

2

There are 2 best solutions below

0
On BEST ANSWER

The indices of a Java String's characters go from 0 to the String's length - 1 (just like the indices of a Java array start in 0, so do the indices of a String).

Therefore in order to print the String in reverse order, the second loop iterates from s.length()-1 to 0. Prior to that, the first loop iterates from 0 to s.length()-1 in order to copy the characters of the String to a character array.

This has nothing to do with multi-dimensional arrays.

0
On

I know you asked for the iterative solution explanation. But, I'll give you the recursive explanation.

public static String reverse(String str) 
{
    if ((str == null) || (str.length() <= 1)) 
        return str;

    return reverse(str.substring(1)) + str.charAt(0);
}

Basically, you check every time the str before calling the function. This is called the base case and is used to stop when the job is completed and not get a stack overflow. Then, afterwards, the functions returns just a section of the original function. At the end, you'll get the str completely reversed as the iterative solution.

Try using the function using System.out.println(reverse("hello"));