根据分隔符将一个长字符串分割保存到动态数组中

// 分隔字符串,ch为分隔符,Source需要分隔的字符串
function SplitString(const source, ch: string): TStringDynArray;
var
  temp: pchar;
  i: Integer;
begin
  Result := nil;
  if source = '' then
    exit;
  temp := pchar(source);
  i := pos(ch, temp);
  while i <> 0 do
  begin
    SetLength(Result, Length(Result) + 1);
    Result[Length(Result) - 1] := copy(temp, 0, i - 1);
    Inc(temp, Length(ch) + i - 1);
    i := pos(ch, temp);
  end;
  SetLength(Result, Length(Result) + 1);
  Result[Length(Result) - 1] := temp;
end;

// 按Seperator分割Source,返回第Index部分,例如:Part('ab|cd|ef','|',1)='cd'
function Part(source, Seperator: string; Index: Integer): string;
var
  SS: TStringDynArray;
begin
  SS := SplitString(source, Seperator);
  if (Index>=Low(SS)) and (Index<=High(SS)) then
    Result := SS[Index]
  else
    Result := '';
end;

posted @ 2012-04-29 06:58  cuibq  阅读(242)  评论(0编辑  收藏  举报