1. Member
Join Date
Nov 2012
Posts
2
Rep Power
0

## 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?

Java 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.

2. Moderator
Join Date
Apr 2009
Posts
11,820
Rep Power
19

## 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)

3. Member
Join Date
Nov 2012
Posts
2
Rep Power
0

## 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?

4. ## Re: Help with Strings

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!

5. Moderator
Join Date
Apr 2009
Posts
11,820
Rep Power
19

## Re: Help with Strings

Java 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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•