Beranda > Delphi > Padding strings

Padding strings

Sometimes you want to format a string with leading or trailing spaces or other characters.  The Pad() function will do that for you.  Say you have a string ‘123’, but you want it to read ‘000123’.  Simply call it like this: tmpStr := Pad(‘123’, 6, ‘0’, _LEADING);type
  PadType = ( _LEADING, _TRAILING );

function Pad (   targetStr: string;
              targetLength: byte;
                   PadChar: string;
                   PadType: PadType ): string;
var
  i,
  startLength: Byte;
begin
  {  Make sure padchar is a 1-char string;  }
  {  default it to the space char.          }
  PadChar := PadChar + ‘ ‘;
  PadChar := copy(PadChar, 1, 1 );

  {  Pad the string  }
  startLength := Length( targetStr );
  if startLength < targetLength then
    for i := startLength + 1 to targetLength do
      begin
        if PadType = _LEADING then
          TargetStr := PadChar + TargetStr
        else
          TargetStr := TargetStr + PadChar;
      end;

  Result := TargetStr;
end;

Iklan
Kategori:Delphi
  1. Belum ada komentar.
  1. No trackbacks yet.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: