分析带分隔符的字符串

真是烦,每次遇到要分析带分隔符字符串的代码时,都要把下面全部重写一遍,费时又费力,可气的是Delphi手册中居然没有此类函数,唉!动手自己写吧,然后加到代码模板里,按Ctrl+j随叫随到,呵呵。想必还有很多人也常遇到这种情况吧。

至于用法就不用我多说了吧,开头的注释很清楚了,您的英文不好可别怪我哟。

 


 

// Description: Extract a field of value from Source string delimited by
//    somewhat delimitor.
// Parameters:
//    [in] Source: specifies the source data;
//    [in] Delim: specifies a charactor as delimitor;
//    [in] Index: specifies a serial number of field you need, which started by zero.
// Return Value:
//    returns the valid string of that field you need if succeeded, otherwise
//  empty string. if Index you passed is more than the maximum number of fields,
//  it also returns empty string.
// Remark: None.
function T|.ExtractDelimitedStr(Source: string; Delim: Char;
  Index: Integer): string;
var
  Src: string;
  ix: Integer;
  PPrev, PNext: PChar;
begin
  if Length (Source) = 0 then Exit;

  Src := Source;
  ix := 0;
  PPrev := PChar (Src);
  PNext := StrScan (PPrev, Delim);

  if PNext = nil then
  begin
  
  Result := Src;
    Exit;
  end;

  while not ((PNext = nil) and (PPrev = nil)) do
  begin
    if ix = Index then
    begin
      if Assigned (PNext) then
        Result := Copy (StrPas (PPrev), 1, PNext - PPrev)
      else
        Result := StrPas (PPrev);
      Exit;
    end;

    if PNext = nil then Exit;

    Delete (Src, 1, PNext - PPrev + 1);
    Inc (ix);
    PPrev := PChar (Src);
    PNext := StrScan (PPrev, Delim);
  end; // end while
end;
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值