0

Anyone know of a good Split procedure that uses StringBuilder in Delphi?

RobertFrank
  • 7,332
  • 11
  • 53
  • 99
  • 5
    What makes you think StringBuilder is an appropriate tool for that job? – Rob Kennedy Feb 12 '10 at 05:20
  • Hi, Rob, Since my implementation was building the tokens by appending one character at a time, I figured StringBuilder would be part of the solution. However, Gerry's StringList.DelimitedText solution works well (and reading its implementation I can see that appending single characters to tokens is a weak solution. I needed speed because I'm reading 1,600 rows of 1,600 tokens, or 2.5 million tokens! – RobertFrank Feb 16 '10 at 01:30

2 Answers2

5

You might be better off using TStringlist.DelimitedText (or any other non-abstract TStrings sub-class). It's more of the traditional Delphi way of achieving what string.Split does in .Net (assuming I remember correctly).

e.g. To split on a pipe | character

var
  SL : TStrings;
  i : integer;
begin
  SL := TStringList.Create;
  try
    SL.Delimiter := '|';
    SL.StrictDelimiter := True;
    SL.DelimitedText := S;
    for i := SL.Count - 1 do
    begin
      // do whatever with sl[i];
    end;
  finally
   SL.Free;
  end;
end;

You may need to handle the QuoteChar property as well

Bruce McGee
  • 15,076
  • 6
  • 55
  • 70
Gerry Coll
  • 5,867
  • 1
  • 27
  • 36
  • 5
    You should set "SL.StrictDelimiter := true;" to make that work. Otherwise Chr(1).. will be taken as delimiters as well. – Uwe Raabe Feb 12 '10 at 08:02
  • Thanks, Gerry. That's MUCH faster than the character by character delete and append I was doing, even with StringBuilder. Looking at the GetDelimitedText code in Classes.pas I see why. I guess marching a pointer through a string REALLY is faster! – RobertFrank Feb 13 '10 at 20:38
0

You can also Look at my answer to this question for a general purpose utility functions GetStringPart and NumStringParts that allow you to perform split type operations.

Community
  • 1
  • 1
skamradt
  • 15,366
  • 2
  • 36
  • 53