Delphi 2009 之 TStringBuilder 类[2]: Append 与 AppendFormat


unit Unit1;



interface



uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

  Dialogs, StdCtrls;



type

  TForm1 = class(TForm)

    Button1: TButton;

    Button2: TButton;

    Button3: TButton;

    Button4: TButton;

    Button5: TButton;

    procedure Button1Click(Sender: TObject);

    procedure Button2Click(Sender: TObject);

    procedure Button3Click(Sender: TObject);

    procedure Button4Click(Sender: TObject);

    procedure Button5Click(Sender: TObject);

  end;



var

  Form1: TForm1;



implementation



{$R *.dfm}



//TStringBuilder.Append 可以添加几乎所有数据类型, 甚至是对象

procedure TForm1.Button1Click(Sender: TObject);

var

  sb1,sb2: TStringBuilder;

  ver: Cardinal;

begin

  sb1 := TStringBuilder.Create;

  sb2 := TStringBuilder.Create;



  sb1.Append('Delphi ');

  ver := 2009;

  sb1.Append(ver);

  ShowMessage(sb1.ToString); {Delphi 2009}



  sb2.Append(sb1);

  {换行}

  sb2.AppendLine;

  sb2.Append(Self);

  ShowMessage(sb2.ToString); {Delphi 2009

                              TForm1}



  sb1.Free;

  sb2.Free;

end;



//TStringBuilder.Append 截取字符数组和字符串

procedure TForm1.Button2Click(Sender: TObject);

const

  CharArr: array[0..6] of Char = ('A','B','C','D','E','F','G');

  Str = 'ABCDEFG';

var

  sb: TStringBuilder;

begin

  sb := TStringBuilder.Create;

  sb.Append(CharArr, 2, 3);

  ShowMessage(sb.ToString); {CDE}



  {清空}

  sb.Length := 0;



  sb.Append(Str, 2, 3);

  ShowMessage(sb.ToString); {CDE}



  sb.Free;

end;



//TStringBuilder.Append 添加指定数目的字符

procedure TForm1.Button3Click(Sender: TObject);

var

  sb: TStringBuilder;

begin

  sb := TStringBuilder.Create;

  sb.Append('A', 10);

  ShowMessage(sb.ToString); {AAAAAAAAAA}

  sb.Free;

end;



//TStringBuilder.Append 试试其他数据类型

procedure TForm1.Button4Click(Sender: TObject);

var

  sb: TStringBuilder;

  b: Boolean;

  r: Real;

begin

  sb := TStringBuilder.Create;



  b := True;

  sb.Append(b);

  sb.AppendLine;

  b := not b;

  sb.Append(b);

  sb.AppendLine;



  r := 100/3;

  sb.Append(r);



  ShowMessage(sb.ToString); {True

                             False

                             33.3333333333333}

  sb.Free;

end;



//TStringBuilder.AppendFormat 的使用和 Format 函数是一样的

procedure TForm1.Button5Click(Sender: TObject);

var

  sb: TStringBuilder;

begin

  sb := TStringBuilder.Create;

  sb.AppendFormat('%s %d', ['Delphi', 2009]);

  ShowMessage(sb.ToString); {Delphi 2009}

  sb.Free;

end;



end.


 
   

你可能感兴趣的:(StringBuilder)