Is there an inverse function of *SysUtils.Format* in Delphi

后端 未结 3 1567
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 20:01

Has anyone written an \'UnFormat\' routine for Delphi?

What I\'m imagining is the inverse of SysUtils.Format and looks something like this

<
3条回答
  •  遥遥无期
    2020-12-09 20:55

    I tend to take care of this using a simple parser. I have two functions, one is called NumStringParts which returns the number of "parts" in a string with a specific delimiter (in your case above the space) and GetStrPart returns the specific part from a string with a specific delimiter. Both of these routines have been used since my Turbo Pascal days in many a project.

    function NumStringParts(SourceStr,Delimiter:String):Integer;
    var
      offset : integer;
      curnum : integer;
    begin
      curnum := 1;
      offset := 1;
      while (offset <> 0) do
        begin
          Offset := Pos(Delimiter,SourceStr);
          if Offset <> 0 then
            begin
              Inc(CurNum);
                Delete(SourceStr,1,(Offset-1)+Length(Delimiter));
            end;
        end;
      result := CurNum;
    end;
    
    function GetStringPart(SourceStr,Delimiter:String;Num:Integer):string;
    var
      offset : integer;
      CurNum : integer;
      CurPart : String;
    begin
      CurNum := 1;
      Offset := 1;
      While (CurNum <= Num) and (Offset <> 0) do
        begin
          Offset := Pos(Delimiter,SourceStr);
          if Offset <> 0 then
            begin
              CurPart := Copy(SourceStr,1,Offset-1);
              Delete(SourceStr,1,(Offset-1)+Length(Delimiter));
              Inc(CurNum)
            end
          else
            CurPart := SourceStr;
        end;
      if CurNum >= Num then
        Result := CurPart
      else
        Result := '';
    end;
    

    Example of usage:

     var
        st : string;
        f1,f2 : double; 
      begin
         st := 'a number 12.35 and another 13.415';
         ShowMessage('Total String parts = '+IntToStr(NumStringParts(st,#32)));
         f1 := StrToFloatDef(GetStringPart(st,#32,3),0.0);
         f2 := StrToFloatDef(GetStringPart(st,#32,6),0.0);
         ShowMessage('Float 1 = '+FloatToStr(F1)+' and Float 2 = '+FloatToStr(F2)); 
      end; 
    

    These routines work wonders for simple or strict comma delimited strings too. These routines work wonderfully in Delphi 2009/2010.

提交回复
热议问题