最近项目中需要如题这样一个方法,在网上搜了下没发现类似的,索性写了一个,还不是很完善。
function SerialStr(Astr: string): string;
var
v_TmpList: TStringList;
v_Index: Integer;
v_ResultList: TStringList;
begin
if Trim(Astr) = EmptyStr then
begin
Result := '无';
Exit;
end;
v_TmpList := TStringList.Create;
v_ResultList:= TStringList.Create;
try
v_TmpList.CommaText := Astr;
for v_Index := 0 to v_TmpList.Count - 1 do
begin
if StrToIntDef(v_TmpList[v_Index],-1) = -1 then
begin
Result := '有非法字符';
Exit;
end;
end;
v_ResultList.Add(v_TmpList[0]);
for v_Index := 0 to v_TmpList.Count - 2 do
begin
if StrToInt(v_TmpList[v_Index + 1]) - StrToInt(v_TmpList[v_Index]) = 1 then
begin
if v_ResultList[v_ResultList.Count - 1] <> '-' then
begin
v_ResultList.Add('-');
end;
end else
begin
if v_ResultList[v_ResultList.Count - 1] = v_TmpList[v_Index] then
begin
v_ResultList.Add(';');
v_ResultList.Add(v_TmpList[v_Index + 1]);
end else
begin
v_ResultList.Add(v_TmpList[v_Index]);
v_ResultList.Add(';');
v_ResultList.Add(v_TmpList[v_Index + 1]);
end;
end;
end;
if v_ResultList[v_ResultList.Count - 1] <> v_TmpList[v_TmpList.count - 1] then
begin
if v_ResultList[v_ResultList.Count - 1] <> '-' then
begin
v_ResultList.Add('-');
v_ResultList.Add(v_TmpList[v_TmpList.count - 1]);
end else
begin
v_ResultList.Add(v_TmpList[v_TmpList.count - 1]);
end;
end;
Result := EmptyStr;
for v_Index := 0 to v_ResultList.Count - 1 do
begin
Result := Result + v_ResultList[v_Index];
end;
finally
v_TmpList.Free;
v_ResultList.Free;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(SerialStr(Edit1.Text));
end;