以递归方式反转字符串

时间:2012-12-25 16:48:15

标签: pascal

我想使用递归函数反转字符串,这是我的代码:

Program InvertTheString;
var n:integer;word:string;

Function Invert (N:integer; word:string) : string;
begin
     if N=1 then
        Invert:=word[N]+Invert
     Else
        Invert:=Invert(N-1,word);
end;

BEGIN
readln(word);
n:=length(word);
writeln (Invert(N,word));

writeln;write('Press Enter To Exit...');
readln;
END.

但它没有用,狼在哪里?

3 个答案:

答案 0 :(得分:3)

Function Invert (N:integer; word:string) : string;
begin
     if N=0 then
        Invert:=''
     Else
        Invert:= word[N] + Invert(N-1,word);
end;

答案 1 :(得分:2)

我不做Pascal,但是伪代码中的典型(简单)递归反转看起来像:

function reverse(word)
  if empty(word) return ""
  else return reverse(withoutFirstLetter(word)) + firstLetterOf(word)

答案 2 :(得分:0)

Function Invert (ch:string) : string;
begin
 if ch='' then
 Invert:=''
 else
 {get the last letter of the string + eliminate it and execute the function}
 Invert:=copy(ch,length(ch),1)+Invert(copy(ch,1,length(ch)-1));
end;