Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove whitespace from a StringList?

I am loading a text file (which contains many lines, some containing spaces or tabs) to a StringList. How can I remove whitespace (excluding newlines) from the entire StringList?

like image 360
NOP Avatar asked Feb 22 '11 13:02

NOP


People also ask

How do I get rid of white space?

To remove all white spaces from String, use the replaceAll() method of String class with two arguments, i.e. Program: Java.

How do I get rid of extra white spaces in a string?

Use replace () function to replace all the space characters with a blank. The resulting string will not have any spaces in-between them.

How do I remove spaces from a string in C++?

To remove whitespace from a string in C++, we can use the std::remove_if function, the std::regex_replace function, or the Boost Library in C++. The erase_all() function in the boost library can be used to remove any specific type of whitespaces from a string.


1 Answers

Here's a crude solution that assumes that tab and space are the only white space characters:

tmp := Strings.Text;
tmp := StringReplace(tmp, #9, '', [rfReplaceAll]);
tmp := StringReplace(tmp, #32, '', [rfReplaceAll]);
Strings.Text := txt;

Here's a more advanced version that will detect any whitespace:

function RemoveWhiteSpace(const s: string): string;
var
  i, j: Integer;
begin
  SetLength(Result, Length(s));
  j := 0;
  for i := 1 to Length(s) do begin
    if not TCharacter.IsWhiteSpace(s[i]) then begin
      inc(j);
      Result[j] := s[i];
    end;
  end;
  SetLength(Result, j);
end;
...
Strings.Text := RemoveWhiteSpace(Strings.Text);

You'll need one of the Unicode versions of Delphi and you'll need to use the Character unit.

If you are using a non-Unicode version of Delphi then you would replace the if with:

if not (s[i] in [#9,#32]) then begin
like image 68
David Heffernan Avatar answered Oct 11 '22 21:10

David Heffernan