delphi 重排字符串问题
假设有这样需要排列的字符串,形式为 01-06-09-05-04 又或者 01,06,09,05,04
需要按从小到大顺序排列出为:01,04,05,06,09
该如何实现?谢谢!
[解决办法]
unit Unit3;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
//现有功能只处理>=0的数值
TCustomSort = class
private
FIndex, FCount : integer;
FDelimiter : Char;
FArr : array of string;
function GetDelimiter(const Value: string): char;
procedure Add(const Value: string);
procedure DoSort;
procedure SetCount(const Value: Integer);
procedure Init;
public
constructor Create;
destructor Destroy; override;
function Sort(const Value : string): string;
end;
TForm3 = class(TForm)
btn1: TButton;
procedure btn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form3: TForm3;
implementation
{$R *.dfm}
procedure TForm3.btn1Click(Sender: TObject);
var
sSourceStr, sDestStr : string;
begin
with TCustomSort.Create do
try
sSourceStr := '01-06-09-05-04-02-110-12';
sDestStr := Sort(sSourceStr);
ShowMessage(sSourceStr + Chr(13) + sDestStr);
sSourceStr := '01,06,09,05,04';
sDestStr := Sort(sSourceStr);
ShowMessage(sSourceStr + Chr(13) + sDestStr);
finally
free;
end;
end;
{ TCustomSort }
procedure TCustomSort.Init;
begin
SetCount(0);
FIndex := 0;
end;
constructor TCustomSort.Create;
begin
Init
end;
destructor TCustomSort.Destroy;
begin
Init;
inherited;
end;
function TCustomSort.GetDelimiter(const Value: string): char;
var
p : pchar;
begin
result := #0;
p := PChar(Value);
while p^ in ['0'..'9'] do
begin
P := CharNext(P);
end;
result := p^;
end;
procedure TCustomSort.DoSort;
var
i, j : integer;
sTemp : string;
begin
for i := 0 to FCount - 2 do
begin
for j := i + 1 to FCount - 1 do
begin
if StrToInt(FArr[i]) > StrToInt(FArr[j]) then
begin
sTemp := FArr[i];
FArr[i] := FArr[j];
FArr[j] := sTemp;
end;
end;
end;
end;
procedure TCustomSort.SetCount(const Value : Integer);
begin
FCount := Value;
SetLength(FArr, FCount);
end;
procedure TCustomSort.Add(const Value: string);
begin
if FCount = FIndex then
SetCount(FCount + 1);
FArr[FIndex] := Value;
Inc(Findex);
end;
function TCustomSort.Sort(const Value: string): string;
var
S : string;
P, P1: PChar;
i : integer;
begin
Init;
Result := '';
//获取分隔符
FDelimiter := GetDelimiter(Value);
if FDelimiter = #0 then
exit;
//装载数据
P := PChar(Value);
while P^ <> #0 do
begin
P1 := P;
while (P^ <> #0) and (P^ <> FDelimiter) do
inc(p);
SetString(S, P1, P - P1);
if (P^ = FDelimiter) then
inc(p);
Add(S);
end;
//排序
DoSort;
//输出结果
for i := 0 to FCount - 1 do
begin
Result := Result + FArr[i] + FDelimiter;
end;
Result := Copy(Result, 1, Length(Result) - 1);
end;
end.