delphi 删除字符串中包含4个以上字母的所有单词(Pascal)?

z6psavjg  于 2022-12-03  发布在  其他
关注(0)|答案(1)|浏览(137)

我被分配了一个任务,为大学,我必须写一个程序,删除所有的单词超过4个字母。我真的没有线索在所有。我会非常感谢任何形式的帮助。

VAR
UserString: string; //должна быть строка на 40 символов и точку в конце
i, n: byte;

BEGIN
Writeln('Enter the string:');
Readln(UserString);

i:=0;
n:=1;    

repeat       //MAIN LOOP:

  inc(i);
  if (UserString[i] = ' ') or (UserString[i] = '.') then

     begin
        if (i-n<3)then
        begin
        delete(UserString, n, i-n+1);
        i:=n-1;
        end;
        n:=i+1
     end

until (UserString[i] = '.') or (i>length(UserString));

Writeln('Result String: ', UserString);
END.

我试过这个。它在onlinegdb上工作,但在 Delphi 上不工作...我不知道为什么...

ffvjumwh

ffvjumwh1#

你应该把逻辑分解成更小的实用函数来完成你所需要的每一个任务(查找单词,获取单词的长度,删除单词和任何后续的空格等),这将使代码更容易阅读和维护。
例如:

function FindNextWordStart(const S: string; var Index: Integer): Boolean;
var
  Len: Integer;
begin
  Len := Length(S);
  while (Index <= Len) and (Ord(S[Index]) <= 32) do Inc(Index);
  Result := (Index <= Len);
end;

function GetWordLength(const S: string; Index: Integer): Integer;
var
  StartIdx, Len: Integer;
begin
  Len := Length(S);
  StartIdx := Index;
  while (Index <= Len) and (Ord(S[Index]) > 32) do Inc(Index);
  Result := (Index - StartIdx);
end;

procedure DeleteWord(var S: String; Index, WordLen: Integer);
var
  StartIdx, Len: Integer;
begin
  Len := Length(S);
  StartIdx := Index;
  Inc(Index, WordLen);
  while (Index <= Len) and (Ord(S[Index]) <= 32) do Inc(Index);
  Delete(S, StartIdx, Index - StartIdx);
end;

var
  UserString: string;
  StartIdx, WordLen: Integer;
begin
  Writeln('Enter the string:');
  Readln(UserString);

  StartIdx := 1;
  while FindNextWordStart(UserString, StartIdx) do
  begin
    WordLen := GetWordLength(UserString, StartIdx);
    if WordLen > 4 then
      DeleteWord(UserString, StartIdx, WordLen)
    else
      Inc(StartIdx, WordLen);
  end;

  Writeln('Result String: ', UserString);
end.

Online Demo

相关问题