unit tools.ParseNumbers;
// http://www.delphipraxis.net/934335-post7.html
interface
uses
System.Generics.Collections;
function ExtractString(
Var aString:
string;
const aDelimiter:
string):
string;
function CreateNumberList(aNumberDesc:
string; aNumberList: TList<Integer>): Boolean;
procedure CreateNumberString(
var aNumberDesc:
string; aNumberList: TList<Integer>);
const
ValidCharsString = '
,;-0123456789';
implementation
uses
System.SysUtils, System.StrUtils;
function ExtractString(
Var aString:
string;
const aDelimiter:
string):
string;
Var
P: Integer;
Begin
P := Pos(aDelimiter, aString);
If P = 0
Then
Begin
Result := Trim(aString);
aString := '
';
End
Else
Begin
Result := Trim(Copy(aString, 1, p - 1));
aString := Trim(Copy(aString, p + Length(aDelimiter), MaxInt));
End
End;
procedure TrimString(
var s:
string);
begin
s := Trim(s);
s := ReplaceStr(s, '
-', '
-');
s := ReplaceStr(s, '
- ', '
-');
s := ReplaceStr(s, '
,', '
;');
s := ReplaceStr(s, '
;', '
;');
s := ReplaceStr(s, '
; ', '
;');
s := ReplaceStr(s, '
', '
;');
end;
function CreateNumberList(aNumberDesc:
string; aNumberList: TList<Integer>): Boolean;
Var
numberDesc, rangeStart:
String;
number, p, q : Integer;
Begin
aNumberList.Clear;
TrimString(aNumberDesc);
While aNumberDesc <> '
'
do
Begin
numberDesc := ExtractString(aNumberDesc, '
;');
If TryStrToInt(numberDesc, number)
Then
aNumberList.Add(number)
else
Begin
rangeStart := ExtractString(numberDesc, '
-');
If TryStrToInt(numberDesc, q)
And TryStrToInt(rangeStart, p)
and (p <= q)
Then
For number := p
to q
Do
aNumberList.Add(number)
Else
Exit(False);
End
End;
Result := True;
End;
procedure CreateNumberString(
var aNumberDesc:
string; aNumberList: TList<Integer>);
var
i: Integer;
begin
if aNumberList.Count = 0
then
Exit;
aNumberDesc := '
';
aNumberList.Sort;
i := 0;
while (i < aNumberList.Count)
do
begin
if (i + 2 < aNumberList.Count)
and (aNumberList[i] + 1 = aNumberList[i + 1])
and
(aNumberList[i] + 2 = aNumberList[i + 2])
then
begin
aNumberDesc := aNumberDesc + IntToStr(aNumberList[i]) + '
-';
while (i + 1 < aNumberList.Count)
and (aNumberList[i] + 1 = aNumberList[i + 1])
do
Inc(i);
aNumberDesc := aNumberDesc + IntToStr(aNumberList[i]);
end
else
begin
aNumberDesc := aNumberDesc + IntToStr(aNumberList[i]);
end;
Inc(i);
if i + 1 < aNumberList.Count
then
aNumberDesc := aNumberDesc + '
;';
end;
end;
end.