StrCopy 和 StrECopy 都是复制源 PChar 串到目标 PChar 串, 只是返回值不同;
StrCopy 返回结果的首地址, StrECopy 返回结果的尾(#0)地址.
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;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

//一般用法, 看不出 StrCopy 与 StrECopy 的区别
procedure TForm1.Button1Click(Sender: TObject);
var
  arr: array[0..3] of Char; {假如 PChar 长度是 3, 这里数组要大出一个, PChar 最后还有一个 #0}
begin
  StrCopy(arr, 'ABC');
  ShowMessage(arr);    {ABC}
  
  StrCopy(arr, '123');
  ShowMessage(arr);    {123}

  StrECopy(arr, 'ABC');
  ShowMessage(arr);    {ABC}
  
  StrECopy(arr, '123');
  ShowMessage(arr);    {123}
end;

//测试 StrCopy 及其返回值:
procedure TForm1.Button2Click(Sender: TObject);
var
  p1,p2,p3,p: PChar;
begin
  p1 := '123456789';
  p2 := 'ABC';

  p3 := PChar(StringOfChar(#0, 9)); {这里用 StringOfChar 代替了 GetMem}
  
  p := StrCopy(p3, p1);
  ShowMessageFmt('%s, %s', [p3, p]); {123456789, 123456789}

  p := StrCopy(p3, p2);
  ShowMessageFmt('%s, %s', [p3, p]); {ABC, ABC}

  ShowMessageFmt('%s, %s', [p3+4, p+4]); {56789, 56789}
end;

//测试 StrECopy 及其返回值:
procedure TForm1.Button3Click(Sender: TObject);
var
  p1,p2,p3,p: PChar;
begin
  p1 := '123456789';
  p2 := 'ABC';

  p3 := PChar(StringOfChar(#0, 9)); {这里用 StringOfChar 代替了 GetMem}
  
  p := StrECopy(p3, p1);
  ShowMessageFmt('%s, %s', [p3, p]); {123456789, }

  p := StrECopy(p3, p2);
  ShowMessageFmt('%s, %s', [p3, p+1]); {ABC, 56789}
end;


//可以巧妙利用 StrECopy 的返回值:
procedure TForm1.Button4Click(Sender: TObject);
var
  p: PChar;
begin
  GetMem(p, 10);

  StrECopy(StrECopy(p,'12345'), '67890');
  ShowMessage(p); {1234567890}
  
  FreeMem(p);
end;

end.

SysUtils 单元下的公用函数目录

posted on 2008-05-12 21:21  万一  阅读(5221)  评论(1编辑  收藏  举报