Author: Ernesto De Spirito
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
1 type
2 TStringArray = array of string;
3
4 function Split(const str: string;
5 const separator: string = ','): TStringArray;
6 function AnsiSplit(const str: string;
7 const separator: string = ','): TStringArray;
8
9 implementation
10
11 uses sysutils;
12
13 function Split(const str: string;
14 const separator: string): TStringArray;
15 // Returns an array with the parts of "str" separated by "separator"
16 var
17 i, n: integer;
18 p, q, s: PChar;
19 begin
20 SetLength(Result, Occurs(str, separator) + 1);
21 p := PChar(str);
22 s := PChar(separator);
23 n := Length(separator);
24 i := 0;
25 repeat
26 q := StrPos(p, s);
27 if q = nil then
28 q := StrScan(p, #0);
29 SetString(Result[i], p, q - p);
30 p := q + n;
31 inc(i);
32 until q^ = #0;
33 end;
34
35 function AnsiSplit(const str: string;
36 const separator: string): TStringArray;
37 // Returns an array with the parts of "str" separated by "separator"
38 // ANSI version
39 var
40 i, n: integer;
41 p, q, s: PChar;
42 begin
43 SetLength(Result, AnsiOccurs(str, separator) + 1);
44 p := PChar(str);
45 s := PChar(separator);
46 n := Length(separator);
47 i := 0;
48 repeat
49 q := AnsiStrPos(p, s);
50 if q = nil then
51 q := AnsiStrScan(p, #0);
52 SetString(Result[i], p, q - p);
53 p := q + n;
54 inc(i);
55 until q^ = #0;
56 end;
57
58 Example:
59
60 procedure TForm1.Button1Click(Sender: TObject);
61 var
62 a: TStringArray;
63 i: integer;
64 begin
65 a := Split('part1,part2,part3');
66 for i := 0 to Length(a) - 1 do
67 begin // Will show three dialogs
68 ShowMessage(a[i]); // 'part1', 'part2', 'part3'
69 end;
70 end;
You can see an example using a StringList instead of a dynamic array in a separate
article "Splitting a string in a string listdkb://592562043".
Copyright (c) 2001 Ernesto De Spiritomailto:edspirito@latiumsoftware.com
Visit: http://www.latiumsoftware.com/delphi-newsletter.php
|