# Help with Strings

• 11-06-2012, 06:33 AM
EatMyChidori
Help with Strings
So I am trying to write a code that will take in a string and print its exact reverse.

My teacher taught me how to do it with recursion today but i don't really understand it.
Can someone explain this code to me?

Code:

```public String reverse(String s) {     if (s.length() <= 1) {         return s;     }     return reverse(s.substring(1, s.length())) + s.charAt(0); }```
I'm having trouble understanding the last line.
• 11-06-2012, 11:36 AM
Tolls
Re: Help with Strings
That's the recursion part.
Do you know what these two parts do?
substring(1, s.length())
and
s.charAt(0)
• 11-06-2012, 08:16 PM
EatMyChidori
Re: Help with Strings
s.charAt(0); returns the first letter. If i input BLACK it would return B

substring(1, s.length()) i don't really understand. It returns the first letter to the length of letters?
• 11-06-2012, 09:42 PM
Re: Help with Strings
Quote:

It returns the first letter to the length of letters?
Close. You noted in the first line that chartAt(0) is the first letter, so substring(1... would be the second letter right?

As always, try it and see! Use your example of the word BLACK and see what you get!
• 11-07-2012, 10:42 AM
Tolls
Re: Help with Strings
Code:

```public String reverse(String s) {     System.out.println("reverse " + s);     if (s.length() <= 1) {         return s;     }     System.out.println("charAt(0) " + s.charAt(0));     return reverse(s.substring(1, s.length())) + s.charAt(0); }```
If you have a way of running the code as a test (which shouldn't be difficult) try the above.
This should show you what each call to reverse is doing.