//压缩字符串
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,zlib, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
Memo2: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function zip(instr:string;var outstr:string):boolean;
var
CS:TCompressionStream;
buffer
char;
MemoStream:TmemoryStream;
strStream:TstringStream;
begin
MemoStream:=TMemoryStream.Create;
strStream:=Tstringstream.Create('');
try
buffer:=pchar(instr);
Cs:=TCompressionStream.Create(clFastest,MemoStream);
try
Cs.Write(buffer^,length(instr));
finally
Cs.Free;
end;
MemoStream.Position :=0;
MemoStream.SaveToStream(strStream);
outstr:=strStream.DataString;
result:=true;
finally
strstream.free;
MemoStream.Free;
end;
end;
function unzip(instr:string;var outstr:string):boolean;
var
c:integer;
DS:TDecompressionStream;
buffer
char;
outbuffer:array [1..512] of byte;
MemoStream:TmemoryStream;
strStream:TstringStream;
begin
MemoStream:=TMemoryStream.Create;
strStream:=Tstringstream.Create('');
DS:=TDecompressionStream.Create(MemoStream);
try
try
buffer:=pchar(instr);
MemoStream.Write(buffer^,length(instr));
MemoStream.Position :=0;
repeat
c:=DS.Read(outbuffer,512);
if c>0 then strStream.Write(outbuffer,c)
until c=0;
finally
ds.Free;
end;
outstr:=strStream.DataString;
result:=true;
finally
strstream.free;
MemoStream.Free;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
s,so:string;
begin
if zip(memo1.Text,s) then
if unzip(s,so) then
memo2.Lines.Text :=so;
end;
end.