程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> Delphi 2009之TStringBuilder類[2]: Append與AppendFormat

Delphi 2009之TStringBuilder類[2]: Append與AppendFormat

編輯:Delphi

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.

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved