zoukankan      html  css  js  c++  java
  • 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;

  • 相关阅读:
    九.Protobuf3特殊类型
    八.Protobuf3更新消息类型(添加新的字段)
    七.Protobuf3 嵌套类型
    六.Protobuf3引入其他.proto文件
    五.Protobuf3 枚举
    四.Protobuf3 缺省值
    VC 在调用main函数之前的操作
    Windows下的代码注入
    C 堆内存管理
    VC++ 崩溃处理以及打印调用堆栈
  • 原文地址:https://www.cnblogs.com/luckForever/p/7255155.html
Copyright © 2011-2022 走看看