Aunque lo hice con fines "didacticos", pienso que se complica demasiado el código haciendo el split en una sola función.
Código Delphi
[-]
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Rtti;
type
PArrInt = ^TArrInt;
TArrInt = TArray< Integer >;
PArrDbl = ^TArrDbl;
TArrDbl = TArray< Double >;
PArrStr = ^TArrStr;
TArrStr = TArray< String >;
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
public
function Split(const S: string; const Separator: array of char): T;
function toArrStr(const A: TArrInt): TArrStr; overload; inline;
function toArrStr(const A: TArrDbl): TArrStr; overload; inline;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function TForm1.Split(const S: string; const Separator: array of char): T;
var
i: Integer;
lArrStr: TArrStr;
lArrInt: TArrInt;
lTmpI: Integer;
lArrDbl: TArrDbl;
lTmpD: Double;
begin
if (TypeInfo(T) <> TypeInfo(TArrInt))
and (TypeInfo(T) <> TypeInfo(TArrDbl))
and (TypeInfo(T) <> TypeInfo(TArrStr))
then
raise Exception.Create('¡Tipo generico no manejado!');
lArrStr := S.Split(Separator);
if TypeInfo(T) = TypeInfo(TArrInt) then
begin
SetLength(lArrInt, 0);
for i := 0 to High(lArrStr) do
begin
if not TryStrToInt(lArrStr[i], lTmpI) then
Continue;
SetLength(lArrInt, Length(lArrInt)+1);
lArrInt[Length(lArrInt)-1] := lTmpI;
end;
PArrInt(@Result)^ := lArrInt;
end
else
if TypeInfo(T) = TypeInfo(TArrDbl) then
begin
SetLength(lArrDbl, 0);
for i := 0 to High(lArrStr) do
begin
if not TryStrToFloat(lArrStr[i], lTmpD) then
Continue;
SetLength(lArrDbl, Length(lArrDbl)+1);
lArrDbl[Length(lArrDbl)-1] := lTmpD;
end;
PArrDbl(@Result)^ := lArrDbl;
end
else
if TypeInfo(T) = TypeInfo(TArrStr) then
PArrStr(@Result)^ := lArrStr;
end;
function TForm1.toArrStr(const A: TArrInt): TArrStr;
var
i: Integer;
begin
for i := 0 to High(A) do
begin
SetLength(Result, Length(Result)+1);
Result[Length(Result)-1] := IntToStr(A[i]);
end;
end;
function TForm1.toArrStr(const A: TArrDbl): TArrStr;
var
i: Integer;
begin
for i := 0 to High(A) do
begin
SetLength(Result, Length(Result)+1);
Result[Length(Result)-1] := FloatToStr(A[i]);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
const
_INT = '1;100;1000;10000;100000';
_DBL = '1,1;1,2;1,3;1,4;1,5';
_STR = 'A;B;C;D;E';
var
lArrI: TArrInt;
lArrD: TArrDbl;
lArrS: TArrStr;
begin
lArrI := Split< TArrInt >(_INT, [';']);
lArrD := Split< TArrDbl >(_DBL, [';']);
lArrS := Split< TArrStr >(_STR, [';']);
Memo1.Lines.Clear;
Memo1.Lines.AddStrings(toArrStr(lArrI));
Memo1.Lines.AddStrings(toArrStr(lArrD));
Memo1.Lines.AddStrings(lArrS);
end;
end.
Resultado:
Código:
1
100
1000
10000
100000
1,1
1,2
1,3
1,4
1,5
A
B
C
D
E