将一个字符串格式化为 Delphi DFM 格式的字符串

function StrToDFMStr(S: UnicodeString): UnicodeString;
  var
    AHelper: TStringBuilder;
    ps, ls: PWideChar;
    L: Integer;
    AQuoterNeeded: Boolean;
  const
    LineLength: Integer = 64;
  begin
    ps := PWideChar(S);
    AHelper := TStringBuilder.Create;
    try
      L := 0;
      AHelper.Append('''');
      AQuoterNeeded := True;
      while ps^ <> #0 do
      begin
        if AHelper.Length - L > LineLength then
        begin
          if AQuoterNeeded then
            AHelper.Append('''');
          AHelper.Append(SLineBreak);
          L := AHelper.Length;
        end;
        if (ps^ >= ' ') and (ps^ <> '''') and (ps^ < #$128) then
        begin
          AHelper.Append(ps^);
          AQuoterNeeded := True;
        end
        else
        begin
          begin
            if AQuoterNeeded then
              AHelper.Append('''');
            AHelper.Append('#').Append(Ord(ps^));
            AQuoterNeeded := False;
          end;
        end;
        Inc(ps);
      end;
      if AQuoterNeeded then
        AHelper.Append('''');
      Result := AHelper.ToString;
    finally
      FreeAndNil(AHelper);
    end;
  end;

 

分享到: