根据输入数字串,返回连续的数字组合,比如输入“1,2,3,5,6,9”返回“1-3;5-6;9” Delphi6实现

最近项目中需要如题这样一个方法,在网上搜了下没发现类似的,索性写了一个,还不是很完善。

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;


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值