tags:

views:

377

answers:

2

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

+5  A: 

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

Gerry
You should set "SL.StrictDelimiter := true;" to make that work. Otherwise Chr(1)..<space> will be taken as delimiters as well.
Uwe Raabe
+1 @Uwe: that has bitten so many people without them noticing...
Jeroen Pluimers
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!
Tom1952
A: 

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.

skamradt