[fpc-pascal] splitting string into array
Michael Van Canneyt
michael at freepascal.org
Wed Jul 11 12:09:40 CEST 2007
On Tue, 10 Jul 2007, Marc Santhoff wrote:
> Am Dienstag, den 10.07.2007, 14:56 +0200 schrieb Andrea Mauri:
> > I used this, check it.
> >
> > // Returns an array with the parts of "str" separated by "separator"
> > function Split(const str: string; const separator: string): array of string;
> > var
> > i, n: integer;
> > strline, strfield: string;
> > begin
> > n:= Occurs(str, separator);
> > SetLength(Result, n + 1);
> > i := 0;
> > strline:= str;
> > repeat
> > if Pos(separator, strline) > 0 then
> > begin
> > strfield:= Copy(strline, 1, Pos(separator, strline) - 1);
> > strline:= Copy(strline, Pos(separator, strline) + 1,
> > Length(strline) - pos(separator,strline));
> > end
> > else
> > begin
> > strfield:= strline;
> > strline:= '';
> > end;
> > Result[i]:= strfield;
> > Inc(i);
> > until strline= '';
> > if Result[High(Result)] = '' then SetLength(Result, Length(Result) -1);
> > end;
>
> Pretty cool, thank you very much.
>
> > andrea
> >
> > Wolfram Kläger ha scritto:
> > > Here is a Delphi implementation of the common PHP function 'explode'.
> > >
> > > http://www.michael-puff.de/Developer/Delphi/Code-Snippets/Explode.html
>
> I'll look at that one, too. Maybe someday my arrays grow and speed
> becomes an issue - better to check which one is fastest.
>
> Wouldn't this function be a candidate for crawling into the 'strutils'
> unit?
Probably, but I would change the interface:
function Split(const str: string; const separator: string; var Res : array of string) : Integer;
So the function returns the number of elements in the array.
The function could also use some speedup. Deleting the parts
which are no longer needed causes a lot of memory fragmentation.
Michael.
More information about the fpc-pascal
mailing list