Wednesday, October 12, 2011

.Net string.format to Delphi StringFormat

Well I have been busy working in .NET and thought to add "string.format" functionality in Delphi. I am not quite sure if this functionality exists in new versions of Delphi??? AFAIK, this is not available until D7.
{------------------------------------------------------------------------
  Procedure: StringFormat
  Author:    Kiran Kurapaty
  Date:      02-Jan-2011
  Arguments: const AFormat: string; AParams: array of const
  Result:    String
  Usage:     ShowMessage(StringFormat( 'Records ({0}) {1} in {2} mins {3} secs ', [123, 'loaded', varMins, varSecs]);  
-------------------------------------------------------------------------}
function StringFormat(const AFormat: string; AParams: array of const): string;
  function GetAsString(varRec: TVarRec): String;
  begin
    try
      case varRec.VType of
        vtAnsiString: result := varRec.VPChar;
        vtBoolean:    result := IfThen(varRec.VBoolean, 'True', 'False');
        vtChar:       result := varRec.VChar;
        vtClass:      result := varRec.VClass.ClassName;
        vtCurrency:   result := format('%m', [varRec.VCurrency^]);
        vtExtended:   result := format('%f', [varRec.VExtended^]);
        vtInt64:      result := format('%d', [varRec.VInt64^]);
        vtInteger:    result := format('%d', [varRec.VInteger]);
        vtInterface:  result := format('%p', [varRec.VPointer]);
        vtObject:     result := varRec.VObject.ClassName;
        vtPChar:      result := varRec.VPChar;
        vtPointer:    result := format('%p', [varRec.VPointer]);
        vtPWideChar:  result := varRec.VPWideChar;
        vtString:     result := varRec.VPChar;
        vtVariant:    result := varRec.VVariant^;
        vtWideChar:   result := varRec.VWideChar;
        vtWideString: result := varRec.VPWideChar;
      end;
    except
      Result := 'Unknown';
    end;
  end;

var
  I: Integer;
  itemVal: string;
begin
  Result := AFormat;
  for I := Low(AParams) to High(AParams) do
  begin
    itemVal := GetAsString(AParams[I]);
    Result := StringReplace(Result, Format('{%d}', [I]), itemVal, [rfReplaceAll]);
  end;
end;

1 comment:

Web Development Company Chennai said...

Nice blog.. Thanks for sharing this blog information with us…