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;

  • 相关阅读:
    战争迷雾Fog Of War
    [UE4]运行时UMG组件跟随鼠标的逻辑:拖拽UMG组件(蓝图)
    [UE4]FString常用API
    用PNG作为Texture创建Material
    [UE4]C++代码操作SplineMesh
    [UE4]Visual Studio的相关插件安装:UE4.natvis和UnrealVS Extension
    TSubobjectPtr和C++传统指针的区别
    组件Slate教程 & UMG widget构造初始化函数中获取其内部组件
    设置UMG的ComboBox(String)字体大小
    UMG设置组件自适应居中或靠边
  • 原文地址:https://www.cnblogs.com/luckForever/p/7255155.html
Copyright © 2011-2022 走看看