0

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

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
KindZadZa
  • 37
  • 5
  • 1
    Arrays start at index `0` and end at index `length - 1`.. That's why the `-1`... It's the same with most programming languages I think... – Codebender Jun 19 '15 at 03:51
  • It is minus one, because the index of the array start at 0. So in order to iterate through the length of the string, you would have to do length minus one to accommodate for that 0th index. – Nicholas Roberts Jun 19 '15 at 03:52
  • I think `sir` is a bit too formal for SOF :) – Jan Groth Jun 19 '15 at 03:59

2 Answers2

2

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

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"));

Luis Lavieri
  • 4,064
  • 6
  • 39
  • 69