Mega Code Archive

 
Categories / Delphi / Examples
 

Trim

Subject: Any simple way to trim spaces from a string? (... Delphi related ...) Here's a little unit that does the job for you: unit TrimStr; { MAR 95, Public Domain version } { Dr. Bob - The Delphi Magazine } interface Const Space = #$20; function LTrim(Str: String): String; function RTrim(Str: String): String; function Trim(Str: String): String; implementation function LTrim(Str: String): String; var len: Byte absolute Str; i: Integer; begin i := 1; while (i < len) and (Str[i] = Space) do Inc(i); LTrim := Copy(Str,i,len-i+1) end {LTrim}; function RTrim(Str: String): String; var len: Byte absolute Str; begin while (Str[len] = Space) do Dec(len); RTrim := Str end {RTrim}; function Trim(Str: String): String; begin Trim := LTrim(RTrim(Str)) end {Trim}; end. Groetjes, Dr. Bob ------------------------------------------------------------------------------- From: pierre@panpan.synapse.net (Pierre Tourigny) Subject: Re: Any simple way to trim spaces from a string? (... Delphi related ...) Date: Fri, 31 Mar 1995 09:29:26 LOCAL The ltrim function doesn't work correctly when the string is all spaces. Replace i < len with i <= len. This works because copy returns an empty string when i > len. (N.B.: The compiler must be in the default mode for boolean evaluation, i.e., short-circuiting).