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?
To remove all white spaces from String, use the replaceAll() method of String class with two arguments, i.e. Program: Java.
Use replace () function to replace all the space characters with a blank. The resulting string will not have any spaces in-between them.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With