Hier die Klasse und deren Implementation:
Delphi-Quellcode:
type
TSplitStrArray = array of String;
type TSplitString = class
private
FString2Split : String;
FSepChar : Char;
FStrings : TSplitStrArray;
FStringsCount : Integer;
FSepPos : array of Integer;
procedure SetSplitString(SplitStr: String);
procedure SetSepChar(sep: Char);
procedure SetSepPos;
procedure SplitString;
public
constructor create(SplitStr: String; sep: Char);
function StringsCount: Integer;
property String2Split: String read FString2Split write SetSplitString;
property SepChar: Char read FSepChar write SetSepChar;
function ReturnSepStrings: TSplitStrArray;
end;
constructor TSplitString.create(SplitStr: String; sep: Char);
var
i : Integer;
begin
FStringsCount := 0;
if SplitStr = '' then
begin
Messagebox(0, 'Die Zeichenfolge ist leer.', 'Hinweis - TSplitString', MB_ICONSTOP);
exit;
end;
if SplitStr[length(SplitStr)] <> sep then
SplitStr := SplitStr+sep;
for i := 0 to length(SplitStr) do
begin
if SplitStr[i] = sep then Inc(FStringsCount);
end;
SetSplitString(SplitStr);
SetSepChar(sep);
SetSepPos;
end;
procedure TSplitString.SetSepPos;
var
i, j : Integer;
begin
j := 0;
setlength(FSepPos, FStringsCount+1);
FSepPos[0] := 0;
for i := 0 to length(FString2Split) do
begin
if FString2Split[i] = FSepChar then
begin
Inc(j);
FSepPos[j] := i;
end;
end;
end;
procedure TSplitString.SetSplitString(SplitStr: String);
begin
if SplitStr = '' then
Messagebox(0, 'Die Zeichenfolge ist leer.', 'Hinweis - TSplitString', MB_ICONINFORMATION);
FString2Split := SplitStr;
end;
procedure TSplitString.SetSepChar(sep: Char);
begin
if sep = '' then
Messagebox(0, 'Das Trennzeichen ist leer.', 'Hinweis - TSpliString', MB_ICONINFORMATION);
FSepChar := sep;
end;
function TSplitString.StringsCount: Integer;
begin
result := FStringsCount;
end;
procedure TSplitString.SplitString;
var
i : Integer;
begin
setlength(FStrings, FStringsCount);
for i := 0 to FStringsCount-1 do
begin
FStrings[i] := copy(FString2Split, FSepPos[i]+1, FsepPos[i+1]-FSepPos[i]-1);
end;
end;
function TSplitString.ReturnSepStrings: TSplitStrArray;
begin
result := FStrings;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
ObjSplitString: TSplitString;
i : Integer;
begin
ObjSplitString := TSplitString.create(Edit1.Text, ';');
try
Label1.Caption := IntToStr(ObjSplitString.StringsCount);
for i := 0 to ObjSplitString.FStringsCount do
begin
Listbox1.Items.Add(IntToStr(ObjSplitString.FSepPos[i]));
end;
ObjSplitString.SplitString;
for i := 0 to ObjSplitString.FStringsCount-1 do
begin
Listbox2.Items.Add(ObjSplitString.FStrings[i]);
end;
finally
ObjSplitString.Free;
end;
end;
Es geht mir um den reinen Entwurf der Klasse nicht um die Implementation der Methoden der Klasse.
Vorallem wie man Fehler Abfangen kann, wenn die zeichenfolge leer ist oder der Separator '' ist.