delphi 中 字符串分割函数 ExtractStringsEx,是ExtractStrings函数的扩展

来源:互联网 发布:大学生淘宝开店卖什么 编辑:程序博客网 时间:2024/05/21 22:22
使用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^=#0or (Strings = nil) then Exit;
  Tail :
= Content;
  InQuote :
= False;
  QuoteChar :
= #0;
  Strings.BeginUpdate;
  
try
    repeat
      
while Tail^ in WhiteSpace + [#13, #10do 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 <> #0and (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^ <> #0then
      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;
原创粉丝点击