zoukankan      html  css  js  c++  java
  • string系列操作

      

    一、Move操作  

    <1> 

    var pSource,pDest:PChar;

         len: integer;

    .......................//一些代码

    Move(pSource,pDest,len); //错误

    Move(pSource^,pDest^,len); //正确,根据Move函数:  S := PChar(@Source);也可以这样

    <2>

    var

    a1,a2:array of char;

    ......
      SetLength(a1,len);
      SetLength(a2,len);

      Move(a1,a2,len);

    //不过总是出现内存错误,应该不是这个缘故。 

      Move(a1[0],a2[0],len);  //这样对

     //////////////////////////////////////////////

     

    var 

       s:string;   

       ps:Pchar; 

       b:pbyte;

       len:integer; 

    begin 

       s:=edit1.Text; //字符串 

       ps:=pchar(s); //转成pchar类型

       len:=length(s);//取字符串长度,占用多少字节 

       getmem(b,len);//申请内存,pchar,pbyte在使用前都必须要申请内存,因为他们是指针

       move(ps^,b^,len);//这里 ps^意思是pchar指向内存数据的第一个字节地址,B^是表示申请内存的第一个字节地址,这样就可以一个一个字节的移到b里去了

       memo1.Text:=pchar(b);//显示

       freemem(b); 

    end; 

    有些人遇到的困惑是为什么 move(s,b,len)不行呢?同样我也遇到这样的困惑

    看了一样move的函数源码才明白

    procedure       Move( const Source; var Dest; count : Integer ); 

    {$IFDEF PUREPASCAL} //SourceDest都是传地址!!!

    var //Move(参数类型对!用法对)

      S, D: PChar; 

      I: Integer; 

    begin 

      S := PChar(@Source);//取内存地址 

      D := PChar(@Dest);//取内存地址 

      if S = D then Exit; 

      if Cardinal(D) > Cardinal(S) then 

        for I := count-1 downto 0 do 

          D[I] := S[I] 

      else 

        for I := 0 to count-1 do 

          D[I] := S[I]; 

    end; 

    如果直接传入s, 

    S := PChar(@Source);//取内存地址 

    就相当于取的字符串S地址的地址

    如果传入的是ps^ 

    S := PChar(@Source);//取内存地址 

    就相当于取pchar 所指向字符串实际数据的地址

     

     

    二、

    string转化为PChar或数组:
    function StrPCopy(Dest: PChar; const Source: string): PChar;

    到数组:

    a1:pchar;

    move(@a1[0],str);

    //拷贝一个 Pascal 类型字符串到一个零终止字符串, 在 32 位 Delphi 中这种类型转换是自动进行的

    PChar或数组转化为string:

    function StrPas(const Str: PChar): string;

    //将零终止字符串转换为 Pascal 类型字符串,在 32 位 Delphi 中这种类型转换是自动进行的

    三、SetLength:string或动态数组

  • 相关阅读:
    2. linux下如何上传和下载文件
    (六)使用Docker镜像(下)
    (五)使用Docker镜像(上)
    1. chmod命令
    阿里P7/P8学习路线图——技术封神之路
    问题二:pip install python-igraph 报错,C core of igraph 没有安装。
    问题一:【Hive】explain command throw ClassCastException in 2.3.4
    (四)docker创建私人仓库
    P5024 保卫王国
    jzoj5980. 【WC2019模拟12.27】字符串游戏
  • 原文地址:https://www.cnblogs.com/760044827qq/p/3768757.html
Copyright © 2011-2022 走看看