大概是这样:
function GetNumStr(str: string): string;
//返回连接数量(1: 就是只有自己)
function GetSeriesNum(StrList: TStrings; StartIndex: Integer): Integer;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{如:1,2,3,5,6,8,11,
要得到这样的结果:1-3,5-6,8,11}
function TForm1.GetNumStr(str: string): string;
const
SPLIT_STR = ',';
var
i, iSeriesNum: Integer;
strList: TStrings;
begin
Result := EmptyStr;
strList := TStringList.Create;
try
//拆分字串到TStringList
ExtractStrings([SPLIT_STR], [], PChar(str), strList);
iSeriesNum := 0;
i := 0;
//for i := 0 to strList.Count - 1 do
while i <= strList.Count - 1 do
begin
iSeriesNum := GetSeriesNum(strList, i);
Case iSeriesNum of
0: Exit;
1:
begin
Result := Result + strList.Strings;
Inc(i);
end;
else
Result := Result + Format('%s-%d',
[strList.Strings, StrToIntDef(strList.Strings, 0) + iSeriesNum - 1]);
Inc(i, iSeriesNum);
end;
Result := Result + ', ';
end;
finally
strList.Free;
end;
end;
function TForm1.GetSeriesNum(StrList: TStrings; StartIndex: Integer): Integer;
var
i, StartNum: Integer;
begin
Result := 0;
with StrList do
begin
if Count < StartIndex then Exit;
StartNum := StrToIntDef(Strings[StartIndex], 0);
for i := StartIndex to Count - 1 do
if StrToIntDef(Strings, 0) > StartNum + i - StartIndex then
Exit
else
Inc(Result);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
memInfo.Lines.Add(GetNumStr('1,2,3,5,6,8,11,13,17,18,19,20'));
end;