• DelphiXE3下的字符串


    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;

  • 相关阅读:
    Python if语句
    Pyhton数据类型总结
    Flask系列之自定义中间件
    Flask系列之蓝图中使用动态URL前缀
    python+Nginx+uWSGI使用说明
    python之threading.local
    python之偏函数
    Flask系列之源码分析(一)
    Python扩展之类的魔术方法
    Flask系列(十一)整合Flask中的目录结构(sqlalchemy-utils)
  • 原文地址:https://www.cnblogs.com/luckForever/p/7255155.html
Copyright © 2020-2023  润新知