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?
How do I remove whitespace from a StringList?
If you remove them, it will be a large single string of the text file. What you want to do with that large string –
Auditory
ah , i don't need that , there is no way that removing spaces from line to line ? :S –
Triumvirate
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
i am using delphi7 is there any chance that i can get work removewhitspace function in delphi 7 ? –
Triumvirate
+1 for preallocating the string (as everyone should do always, but this isn't the case). (I trust you will correct the syntax errors.) –
Bloomington
@david thanks sir it worked great , but u did blunder u used procedure instead of fucntion :) –
Triumvirate
@Triumvirate thanks, fixed it now, I just wrote it info the answer box, didn't bother compiling it, hence the two errors! The memory allocation and indexing is water-tight though - that's the bit I was concentrating on! –
Chickasaw
@Andreas I loathe code that does
SetLength(a, Length(a)+1)
! –
Chickasaw @David, any decent programmer should. –
Bloomington
In Delphi XE+ recommended using
uses System.Character
var C:Char;
for i := 1 to Length(s) do begin C := s[i]; if C.IsWhiteSpace then begin /// ...etc
because IsWhiteSpace function is deprecated as per the documentation link –
Raffia Depending on how much text there is you can use the StringReplace() function on the entire text. Im sure this isnt the most efficient way, however should work.
e.g.
var tmpString : String;
Memo1.LoadFromFile(Filename);
tmpString := StringReplace(memo1.Text, #9, '',[rfReplaceAll]);
Then load the tmpString into the stringlist.
© 2022 - 2024 — McMap. All rights reserved.