Pascal 无限 while 循环

Pascal Infinite while loop

我正在 Win10(64 位)的 FreePascal 中实现一个程序。问题状态:

'Given a string, replace all substring 'child' with 'childhood' '

'Replace all 'child' with 'childhood''

我试试这个程序

uses crt;
var s, newS : string;
    tmp, tmp2, tmp3 : int64;
    tmpstr, tmpstr2 : string;
    step, step2, step3 : longint;
    position : longint;

begin
        clrscr;
        write('Nhap xau : '); readln(s);
        //main mechanism

        while pos('child',s) <> 0 do begin
                position := pos('child', s);
                delete(s, pos('child',1), 5);
                insert('childhood',s,position);
                inc(position, 9);
                newS := '';
                for step:=position to length(s) do begin
                        newS := newS + s[step];
                end;
                s := newS;
        end;
        writeln(s);

        readkey;
end.

你可以看到这部分:

inc(position, 9);
newS := '';
for step:=position to length(s) do begin
        newS := newS + s[step];
end;
s := newS;

曾经试图切断while循环,但是没有用。有什么想法吗?

非常感谢,祝您有愉快的一天!感谢阅读这个问题线程! =)

这只是其中一种可能性,没有优化但可能是最容易理解的:

oldstr := 'original child string';
newstr := '';

while oldstr<>'' do begin
  // analyze the string from left to right
  if copy(oldstr, 1 5)='child' then begin
    // match found, perform substitution
    newstr := newstr+'childhood';
    delete(oldstr, 1, 5)
  end else begin
    // does not match, go ahead to the next possibility
    newstr := newstr+oldstr[1];
    delete(oldstr, 1, 1)
  end
end
// now newstr is the desired result

这里的问题是不要再次分析在上一步(child->childhood)中添加的内容。上面的算法(警告,我没有测试过)确保原始字符串中的任何单个字符只检查一次。