Author: Ronald Buster
Implode & Explode routines just for Dephi making life easy ...
Answer:
1 2 //////////////////////////////////////////////////////////////////////////3 // Procedure - implode4 // Author - Ronald Buster5 // Remarc - PHP like implode function6 //7 // Returns a string containing a string representation of all the array8 // elements in the same order, with the glue string between each element.9 //////////////////////////////////////////////////////////////////////////10 11 function implode(const glue: string; const pieces: arrayofstring): string;
12 var13 I: Integer;
14 begin15 Result := '';
16 for I := 0 to High(Pieces) do17 Result := Result + Glue + Pieces[I];
18 Delete(Result, 1, Length(Glue));
19 end;
20 21 //////////////////////////////////////////////////////////////////////////22 // Procedure - explode23 // Author - Ronald Buster24 // Remarc - PHP like explode function25 //26 // Returns an array of strings, each of which is a substring of string27 // formed by splitting it on boundaries formed by the string separator.28 // If limit is set, the returned array will contain a maximum of limit29 // elements with the last element containing the rest of string.30 //31 //////////////////////////////////////////////////////////////////////////32 33 function explode(const separator, s: string; limit: Integer = 0): TDynStringArray;
34 var35 SepLen: Integer;
36 F, P: PChar;
37 begin38 SetLength(Result, 0);
39 if (S = '') or (Limit < 0) then40 Exit;
41 if Separator = '' then42 begin43 SetLength(Result, 1);
44 Result[0] := S;
45 Exit;
46 end;
47 SepLen := Length(Separator);
48 49 P := PChar(S);
50 while P^ <> #0 do51 begin52 F := P;
53 P := AnsiStrPos(P, PChar(Separator));
54 if (P = nil) or ((Limit > 0) and (Length(Result) = Limit - 1)) then55 P := StrEnd(F);
56 SetLength(Result, Length(Result) + 1);
57 SetString(Result[High(Result)], F, P - F);
58 F := P;
59 while (P^ <> #0) and (P - F < SepLen) do60 Inc(P);
61 end;
62 end;