Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Recursive method

Status
Not open for further replies.

justride

Programmer
Jan 9, 2004
251
US
I have a method that recurivley removed leading character of a passed string that are unwanted. if a character at index 0 in the string is unwanted then I call the method again removing that index 0 untill a character that is wanted is found, then I want to return that string, however the string that is being returned is the very original string. I guess I am not understanding recursion properly?
Code:
 private String chop(String string){
     if ( !( doesCharacterExist(string.charAt(0)) ) ){
            string = string.substring(1,string.length());
            chop(string);
     }
     return string;
 }
If I do a print out on each iteration I see the string get smaller however the return is the original string, If I put an else{ return string } I get the same behavior to. I figured by renaming string I would eliminate the original string's memory, guess not.

Any suggestions?
THanks
 
The problem is that chop(...), upon returning, returns to the previous iteration of chop(...), and so on, until, finally, it is the originally-called instance of chop(...) that returns the original string (or, it looks like, maybe the one with the first character truncated.

change
chop(string);
to
string = chop(string);

That should do it.

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
By the way, recursion is unneficient at runtime and difficult to read and maintain.

Cheers,
Dian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top