Author: Jonas Bilinkevicius
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.
1
2 function MemoTrimTrail(const aMemo: string): string;
3 var
4 iRead, iWrite, vLastNonWhite, vLastNonSpace: Integer;
5 vChr: Char;
6 vIsSpace, vIsReturn: Boolean;
7 begin
8 if aMemo = '' then
9 begin {empty string}
10 Result := ''; {nothing to do}
11 exit;
12 end;
13 SetLength(Result, Length(aMemo)); {initially, empty string of same length}
14 UniqueString(Result); {make sure we have a separate copy}
15 iWrite := 0; {where characters will be written out}
16 vLastNonWhite := 0; {last non-space, non-return}
17 vLastNonSpace := 0; {last non-space, but could be return}
18 for iRead := 1 to Length(aMemo) do
19 begin
20 vChr := aMemo[iRead]; {pick next char in source}
21 vIsReturn := vChr in [#13, #10]; {CR or LF}
22 vIsSpace := vChr in [#32, #09]; {space or tab}
23 if vIsReturn then
24 iWrite := vLastNonSpace + 1 {skip empty end-of-lines}
25 else
26 Inc(iWrite);
27 Result[iWrite] := vChr; {write char in result-string}
28 if not vIsSpace then
29 begin
30 vLastNonSpace := iWrite; {last non-space, returns are Ok}
31 if not vIsReturn then
32 begin
33 vLastNonWhite := iWrite; {last black-ink character}
34 end;
35 end;
36 end;
37 SetLength(Result, vLastNonWhite); {truncate at last black-ink character}
38 end;
|