Format

本文摘自《大富翁论坛》blyb

格式化字符串
使用加号(+)操作符和转换函数(如IntToStr),你确实能把已有值组合成字符串,不过另有一种方法能格式化数字、货币值和其他字符串,这就是功能强大的Format函数及其一族。

Format函数参数包括:一个基本文本字符串、一些占位符(通常由%符号标出)和一个数值数组,数组中每个值对应一个占位符。例如,把两个数字格式化为字符串的代码如下:

Format('First%d,Second%d',[n1,n2]);
其中n1和n2是两个整数值,第一个占位符由第一个值替代,第二个占位符由第二个值替代,以此类推。如果占位符输出类型(由%符号后面的字母表示)与对应的参数类型不匹配,将产生一个运行时间错误,因此设置编译时间类型检查会有利于Format函数的使用。

除了%d外,Format函数还定义了许多占位符。这些占位符定义了相应数据类型的默认输出,你可以用更深一层的格式化约束改变默认输出,例如一个宽度约束决定了输出中的字符个数,而精度约束决定了小数点的位数。例如

Format('%8d',[n1]);
该句把数字n1转换成有8个字符的字符串,并通过填充空白使文本右对齐,左对齐用减号(-)。

占位符说明
d(decimal)将整型值转换为十进制数字字符串
x(hexadecimal)将整型值转换为十六进制数字字符串
p(pointer)将指针值转换为十六进制数字字符串
s(string)拷贝字符串、字符、或字符指针值到一个输出字符串
e(exponential)将浮点值转换为指数表示的字符串
f(floatingpoint)将浮点值转换为浮点表示的字符串
g(general)使用浮点或指数将浮点值转换为最短的十进制字符串
n(number)将浮点值转换为带千位分隔符的浮点值
m(money)将浮点值转换为现金数量表示的字符串,转换结果取决于地域设置,详见Delphi帮助文件的Currencyanddate/timeformattingvariables主题

举两例:

This example displays a message on the form's status bar indicating the record count after a record is deleted.

procedure TForm1.MyDataAfterDelete(DataSet: TDataSet);
begin
  StatusBar1.SimpleText := Format('There are now %d records in the table', [DataSet.RecordCount]);
end;  



This example copies a specified file into the same directory as the (cross-platform) application.


procedure TForm1.Save1Click(Sender: TObject);

var
  NewFileName: string;
  Msg: string;
  NewFile: TFileStream;
  OldFile: TFileStream;
begin
  NewFileName := ExtractFilePath(Application.ExeName) + ExtractFileName(Edit1.Text);
  Msg := Format('Copy %s to %s?', [Edit1.Text, NewFileName]);
  if MessageDlg(Msg, mtCustom, mbOKCancel, 0) = mrOK then
  begin
    OldFile := TFileStream.Create(Edit1.Text, fmOpenRead or fmShareDenyWrite);
    try
      NewFile := TFileStream.Create(NewFileName, fmCreate or fmShareDenyRead);

      try
        NewFile.CopyFrom(OldFile, OldFile.Size);
      finally
        FreeAndNil(NewFile);
      end;
    finally
      FreeAndNil(OldFile);
    end;
  end;

end;  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值