How to remove multiple spaces from a string in Pascal

2 Answers

0 votes
// Manual loop (works everywhere)

program RemoveMultipleSpaces;

{$mode objfpc}{$H+}

function RemoveExtraSpaces(const S: string): string;
var
  i: Integer;
  lastWasSpace: Boolean;
begin
  Result := '';
  lastWasSpace := False;

  for i := 1 to Length(S) do
  begin
    if S[i] = ' ' then
    begin
      if not lastWasSpace then
        Result := Result + ' ';
      lastWasSpace := True;
    end
    else
    begin
      Result := Result + S[i];
      lastWasSpace := False;
    end;
  end;
end;

begin
  WriteLn(RemoveExtraSpaces('Hello    world   this   is   Pascal'));
end.



(* run:

Hello world this is Pascal

*)

 



answered 23 hours ago by avibootz
edited 23 hours ago by avibootz
0 votes
// Using SysUtils.StringReplace with a loop

program RemoveMultipleSpaces;

{$mode objfpc}{$H+}

uses SysUtils;

function CollapseSpaces(S: string): string;
begin
  repeat
    S := StringReplace(S, '  ', ' ', [rfReplaceAll]);
  until Pos('  ', S) = 0;
  Result := S;
end;

begin
  WriteLn(CollapseSpaces('Hello    world   this   is   Pascal'));
end.




(* run:

Hello world this is Pascal

*)

 



answered 23 hours ago by avibootz
...