Ashref
Ashref

Reputation: 319

Pascal : inverting a string with recursion

I'm trying to learn recursion in pascal, and i have this code to invert a string with recursion :

Function Invert (ch:string) : string;

    begin
     if ch='' then
     Invert:=''
     else

     Invert:=copy(ch,length(ch),1)+Invert(copy(ch,1,length(ch)-1));
    end;

Can anyone explain to me what's going on here step by step. Thank you.

Upvotes: 1

Views: 320

Answers (1)

Scott Hunter
Scott Hunter

Reputation: 49893

If the string is empty, its inversion is just the empty string; otherwise, the inversion is the last character followed by the inversion of (the string minus its last character).

Fortunately, you have a function that can invert a string: Invert.

Upvotes: 3

Related Questions