真是烦,每次遇到要分析带分隔符字符串的代码时,都要把下面全部重写一遍,费时又费力,可气的是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 whileend;
