Mirror

Splitting a string in an dynamic array (Views: 101)


Problem/Question/Abstract:

A function that splits a string in parts separated by a substring and returns the parts in a dynamic string array

Answer:

The following functions split a string in parts separated by a substring and return the parts in a dynamic string array:

interface

type
  TStringArray = array of string;

function Split(const str: string;
  const separator: string = ','): TStringArray;
function AnsiSplit(const str: string;
  const separator: string = ','): TStringArray;

implementation

uses sysutils;

function Split(const str: string;
  const separator: string): TStringArray;
// Returns an array with the parts of "str" separated by "separator"
var
  i, n: integer;
  p, q, s: PChar;
begin
  SetLength(Result, Occurs(str, separator) + 1);
  p := PChar(str);
  s := PChar(separator);
  n := Length(separator);
  i := 0;
  repeat
    q := StrPos(p, s);
    if q = nil then
      q := StrScan(p, #0);
    SetString(Result[i], p, q - p);
    p := q + n;
    inc(i);
  until q^ = #0;
end;

function AnsiSplit(const str: string;
  const separator: string): TStringArray;
// Returns an array with the parts of "str" separated by "separator"
// ANSI version
var
  i, n: integer;
  p, q, s: PChar;
begin
  SetLength(Result, AnsiOccurs(str, separator) + 1);
  p := PChar(str);
  s := PChar(separator);
  n := Length(separator);
  i := 0;
  repeat
    q := AnsiStrPos(p, s);
    if q = nil then
      q := AnsiStrScan(p, #0);
    SetString(Result[i], p, q - p);
    p := q + n;
    inc(i);
  until q^ = #0;
end;

Example:

procedure TForm1.Button1Click(Sender: TObject);
var
  a: TStringArray;
  i: integer;
begin
  a := Split('part1,part2,part3');
  for i := 0 to Length(a) - 1 do
  begin // Will show three dialogs
    ShowMessage(a[i]); // 'part1', 'part2', 'part3'
  end;
end;

You can see an example using a StringList instead of a dynamic array in a separate article "Splitting a string in a string list".


Copyright (c) 2001 Ernesto De Spirito
Visit: http://www.latiumsoftware.com/delphi-newsletter.php

<< Back to main page