Author: Jonas Bilinkevicius
I need to be able to search through a list of strings and remove the ones that only
contain what I call "white space" - spaces, tabs, control chars, etc.. Is there a
function (either Delphi or WinAPI) that will do this?
Answer:
Solve 1:
1 procedure RemoveBlanks(sl: TStringList);
2 var3 i, j: Integer;
4 blank: Boolean;
5 c: Char;
6 chars: array[Char] of Boolean;
7 begin8 { Set all significant chars to false }9 FillChar(chars, SizeOf(chars), True);
10 for c := 'A' to 'Z' do11 chars[c] := False;
12 for c := 'a' to 'z' do13 chars[c] := False;
14 for c := '0' to '9' do15 chars[c] := False;
16 i := Pred(sl.Count);
17 while (i >= 0) do18 begin19 blank := True;
20 j := Length(sl[i]);
21 while (blank and (j >= 0)) do22 begin23 blank := blank and chars[sl[i][j]];
24 Dec(j);
25 end;
26 if blank then27 sl.Delete(i);
28 Dec(i);
29 end;
30 end;
Solve 2:
31 procedure DeleteWhiteLines(Strings: TStrings);
32 var33 I: Integer;
34 begin35 for I := Strings.Count - 1 downto 0 do36 if TrimLeft(Strings[I]) = '' then37 Strings.Delete(I);
38 end;
Solve 3:
39 function KeepStr(sSource: string; ValidChars: TCharSet): string;
40 var41 iCurPos: Integer;
42 begin43 Result := Trim(sSource);
44 iCurPos := 1;
45 if Length(Result) > 0 then46 begin47 repeat48 if Result[iCurPos] in ValidChars then49 Inc(iCurPos)
50 else51 Delete(Result, iCurPos, 1);
52 if length(Result) = 0 then53 break;
54 until (iCurPos = Length(Result) + 1);
55 end;
56 end;
57 58 //You use KeepStr like this:59 60 type61 TCharSet = setof char;
62 63 var64 i: integer;
65 s: string;
66 begin67 {AList is a TStringList declared somewhere}68 {have to work from the end of the list}69 for i := pred(AList) downto 0 do70 begin71 s := AList[i];
72 s := KeepStr(s, ['A'..'Z'] + ['a'..'z'] + ['0'..'9']);
73 if s = '' then74 AList.Delete(i);
75 end;
76 end;