

-----------------------------------

a22asin

Sat Nov 30, 2013 11:21 am


Reversing character and Words in a String.

-----------------------------------

HI, im having a bit of trouble with this assignment where i have to reverse the characters in a word as well as the word itself in a string given by the user. The hard part about it is that i have to do it using a recursive method. Im new to java, and having quite a bit of trouble adjusting to it. lol. Anywho, i managed to get it to reverse the characters in the 1st string, but not in the whole string, and nor could i manage to reverse the ordering of the words (ie. I love comp sci = ics evol I). Thi is what i got:

[code]
  public static String reverseWord(String s) {
			if (s.length() == 1) {
				return s;
			}else {
				char c = s.charAt(0);
				return (s.substring(1)) + c;
			}
	}
[/code]


-----------------------------------

Raknarg

Sat Nov 30, 2013 11:46 am


RE:Reversing character and Words in a String.

-----------------------------------

First of all, it looks like this will work if you have a 1 or 2 letter word. However, the thing is that you are only going through this once. 

Eg. s = "hi"

it puts the h at the end and puts the i first, so "ih"

Eg. s = "hello"

It puts the h at the end, but now it will put "ello" in front of it. So, "elloh"

Ever Have you ever used resursion? You're very, very close to solving it.


-----------------------------------

a22asin

Sat Nov 30, 2013 12:16 pm


RE:Reversing character and Words in a String.

-----------------------------------

No i have never used recursion. My code is based on some research and wha i learned in class. But it has only taken me this far, from here i have no idea what to do unfortunately.


-----------------------------------

crossley7

Sat Nov 30, 2013 12:55 pm


RE:Reversing character and Words in a String.

-----------------------------------

By definition, a recursive function will call itself.  You are extremely close with your code there.  Just find what you need to call the function with to get it to continue reversing the rest of the string.


-----------------------------------

Raknarg

Sat Nov 30, 2013 1:05 pm


RE:Reversing character and Words in a String.

-----------------------------------

Well, I'll give you a simple example of recursion. An easy example would be factorials. 

2! = 1x2
4! = 1x2x3x4
9! = 1x2x3x4x5x6x7x8x9

and so on.

public static int factorial(int n) {
   if (n 