Mirror

How to remove white-spaces from a string (Views: 705)


Problem/Question/Abstract:

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:

procedure RemoveBlanks(sl: TStringList);
var
  i, j: Integer;
  blank: Boolean;
  c: Char;
  chars: array[Char] of Boolean;
begin
  { Set all significant chars to false }
  FillChar(chars, SizeOf(chars), True);
  for c := 'A' to 'Z' do
    chars[c] := False;
  for c := 'a' to 'z' do
    chars[c] := False;
  for c := '0' to '9' do
    chars[c] := False;
  i := Pred(sl.Count);
  while (i >= 0) do
  begin
    blank := True;
    j := Length(sl[i]);
    while (blank and (j >= 0)) do
    begin
      blank := blank and chars[sl[i][j]];
      Dec(j);
    end;
    if blank then
      sl.Delete(i);
    Dec(i);
  end;
end;


Solve 2:

procedure DeleteWhiteLines(Strings: TStrings);
var
  I: Integer;
begin
  for I := Strings.Count - 1 downto 0 do
    if TrimLeft(Strings[I]) = '' then
      Strings.Delete(I);
end;


Solve 3:

function KeepStr(sSource: string; ValidChars: TCharSet): string;
var
  iCurPos: Integer;
begin
  Result := Trim(sSource);
  iCurPos := 1;
  if Length(Result) > 0 then
  begin
    repeat
      if Result[iCurPos] in ValidChars then
        Inc(iCurPos)
      else
        Delete(Result, iCurPos, 1);
      if length(Result) = 0 then
        break;
    until (iCurPos = Length(Result) + 1);
  end;
end;

You use KeepStr like this:

type
  TCharSet = set of char;

var
  i: integer;
  s: string;
begin
  {AList is a TStringList declared somewhere}
  {have to work from the end of the list}
  for i := pred(AList) downto 0 do
  begin
    s := AList[i];
    s := KeepStr(s, ['A'..'Z'] + ['a'..'z'] + ['0'..'9']);
    if s = '' then
      AList.Delete(i);
  end;
end;

<< Back to main page