2009. augusztus 26., szerda

How to remove white-spaces from a TMemo


Problem/Question/Abstract:

How to remove white-spaces from a TMemo

Answer:

This would trim a TMemo (multi-line string), discarding any white-space from end-of-lines and from end-of-text. The end result is exactly similar to the original, without the useless extras, usually left-overs from bad typing habits.

function MemoTrimTrail(const aMemo: string): string;
var
  iRead, iWrite, vLastNonWhite, vLastNonSpace: Integer;
  vChr: Char;
  vIsSpace, vIsReturn: Boolean;
begin
  if aMemo = '' then
  begin {empty string}
    Result := ''; {nothing to do}
    exit;
  end;
  SetLength(Result, Length(aMemo)); {initially, empty string of same length}
  UniqueString(Result); {make sure we have a separate copy}
  iWrite := 0; {where characters will be written out}
  vLastNonWhite := 0; {last non-space, non-return}
  vLastNonSpace := 0; {last non-space, but could be return}
  for iRead := 1 to Length(aMemo) do
  begin
    vChr := aMemo[iRead]; {pick next char in source}
    vIsReturn := vChr in [#13, #10]; {CR or LF}
    vIsSpace := vChr in [#32, #09]; {space or tab}
    if vIsReturn then
      iWrite := vLastNonSpace + 1 {skip empty end-of-lines}
    else
      Inc(iWrite);
    Result[iWrite] := vChr; {write char in result-string}
    if not vIsSpace then
    begin
      vLastNonSpace := iWrite; {last non-space, returns are Ok}
      if not vIsReturn then
      begin
        vLastNonWhite := iWrite; {last black-ink character}
      end;
    end;
  end;
  SetLength(Result, vLastNonWhite); {truncate at last black-ink character}
end;

Nincsenek megjegyzések:

Megjegyzés küldése