使用ExtractStrings函数发现不能分割出空串,很是郁闷,发现delphi提供ExtractStrings的代码,打开看看修改了一下,实现增加空串的功能,如下
function ExtractStringsEx(Separators, WhiteSpace: TSysCharSet; Content: PChar;
Strings: TStrings): Integer;
var
Head, Tail: PChar;
EOS, InQuote: Boolean;
QuoteChar: Char;
Item: string;
begin
Result := 0;
if (Content = nil) or (Content^=#0) or (Strings = nil) then Exit;
Tail := Content;
InQuote := False;
QuoteChar := #0;
Strings.BeginUpdate;
try
repeat
while Tail^ in WhiteSpace + [#13, #10] do Tail := StrNextChar(Tail); //忽略每个分割前面的字符
Head := Tail;
while True do
begin
while (InQuote and not (Tail^ in [QuoteChar, #0])) or
not (Tail^ in Separators + [#0, #13, #10, '''', '"']) do Tail := StrNextChar(Tail);
if Tail^ in ['''', '"'] then
begin
if (QuoteChar <> #0) and (QuoteChar = Tail^) then
QuoteChar := #0
else if QuoteChar = #0 then
QuoteChar := Tail^;
InQuote := QuoteChar <> #0;
Tail := StrNextChar(Tail);
end else Break;
end;
EOS := Tail^ = #0;
if (Head <> Tail) and (Head^ <> #0) then
begin
if Strings <> nil then
begin
SetString(Item, Head, Tail - Head);
Strings.Add(Item);
end;
Inc(Result);
end
else if Head^ <> #0 then //如果头尾相同则增加空串 else if 后面的内容是我增加的
begin
if Strings <> nil then
Strings.Add('');
Inc(Result);
end;
Tail := StrNextChar(Tail);
until EOS;
finally
Strings.EndUpdate;
end;
end;
Strings: TStrings): Integer;
var
Head, Tail: PChar;
EOS, InQuote: Boolean;
QuoteChar: Char;
Item: string;
begin
Result := 0;
if (Content = nil) or (Content^=#0) or (Strings = nil) then Exit;
Tail := Content;
InQuote := False;
QuoteChar := #0;
Strings.BeginUpdate;
try
repeat
while Tail^ in WhiteSpace + [#13, #10] do Tail := StrNextChar(Tail); //忽略每个分割前面的字符
Head := Tail;
while True do
begin
while (InQuote and not (Tail^ in [QuoteChar, #0])) or
not (Tail^ in Separators + [#0, #13, #10, '''', '"']) do Tail := StrNextChar(Tail);
if Tail^ in ['''', '"'] then
begin
if (QuoteChar <> #0) and (QuoteChar = Tail^) then
QuoteChar := #0
else if QuoteChar = #0 then
QuoteChar := Tail^;
InQuote := QuoteChar <> #0;
Tail := StrNextChar(Tail);
end else Break;
end;
EOS := Tail^ = #0;
if (Head <> Tail) and (Head^ <> #0) then
begin
if Strings <> nil then
begin
SetString(Item, Head, Tail - Head);
Strings.Add(Item);
end;
Inc(Result);
end
else if Head^ <> #0 then //如果头尾相同则增加空串 else if 后面的内容是我增加的
begin
if Strings <> nil then
Strings.Add('');
Inc(Result);
end;
Tail := StrNextChar(Tail);
until EOS;
finally
Strings.EndUpdate;
end;
end;