DelphiXE3下的字符串

来源:互联网 发布:gbk转utf java 编辑:程序博客网 时间:2024/05/22 18:23

DelphiXE3下的字符


在delphi中,我们常用String来声明字符串.

procedure TestStringForDelphi;
var
   strName: String;
   nLenName: Integer;
begin
   strName := '中国a';
   nLenName := Length(strName);

   ShowMessage('字符串"' + strName +  '"长度为:' + IntToStr(nLenName) +';第一个字符是:' + strName[1]);

end;


1、在Delphi7中显示结果


也就是说在delphi7中,String代表的是AnsiString类型;Length得到的是字符串的字节长度,strName[1]得到的是字符串的第一个字节,因为汉字占用两个字节,所以没有显示“中”这个字符


2、在DelphiXE3中显示结果


也就是说在delphixe3中,String代表的是WideString类型;Length得到的是字符串的字符长度,strName[1]得到的是字符串的第一个字符,想得到字符串的字节长度,可使用System.SysUtils.ByteLength(strName)函数。

我们来看一下ByteLength的实现:

function ByteLength(const S: string): Integer;
begin
  Result := Length(S) * SizeOf(Char);
end;

发现了什么?计算结果是:字符长度*SizeOf(Char),而SizeOf(Char)=2,因为Char类型在DelphiXE3下代表的是WideChar,占用两个字节的空间。


3、DelphiXE3下的字符串流操作

// 将字符串写入流

procedure WriteStringToStream(AStream: TStream; Const AStr: String);
var
  nByteCnt: Integer;
begin
  nByteCnt := ByteLength(AStr);

  AStream.WriteBuffer(nByteCnt, SizeOf(nByteCnt));

  AStream.WriteBuffer(AStr[1], nByteCnt);
end;

// 从流中读取字符串
procedure ReadStringFromStream(AStream: TStream; Var AStr: String);
var
  nByteCnt,
 nCharCnt: Integer;

begin
  AStream.ReadBuffer(nByteCnt, SizeOf(nByteCnt));

  nCharCnt := nByteCnt div 2;

  SetLength(AStr, nCharCnt);

  if nByteCnt > 0 then
    AStream.ReadBuffer(AStr[1], nByteCnt);
end;


4、DelphiXE3下的字符串和字节数组的转换

procedure GetBytesFromString(Value: String);

var
    StrBuf: TBytes;
begin

    StrBuf := System.SysUtils.TEncoding.UTF8.GetBytes(Value);

end;


procedure GetStringFromBytes(Value: TBytes);

var

    str: String;

begin

    Str := System.SysUtils.TEncoding.UTF8.GetString(Value);

end;