Parsing strings
From Morfikwiki.com
Contents |
[edit] Introduction
This describes how you can use TArray to parse a string into an array of smaller string sequences.
[edit] Notes
- In the PHP world, this is equivalent to the Explode function.
- Two independent versions are given depending on whether you wish for this functionality on the browser-side or the server-side of your application.
- Although the algorithm for this parser is very basic, it outlines some of the subtle differences between string manipulation in the browser-side and the server-side.
[edit] Server-side Solution
{...............................................................................}
TListReader = Class(TStringList)
Procedure Readlist(Lst : String; aDelimiter : Char);
End;
{...............................................................................}
Implementation
{...............................................................................}
Procedure TListReader.Readlist(Lst : String; aDelimiter : Char);
Begin
Delimiter := aDelimiter;
SetDelimitedText(Lst);
End;
{...............................................................................}
{...............................................................................}
Procedure Caller(Sender: TWebDocument; Var PContinue: Boolean);
Var
Lst : TListReader;
S : String;
i : Integer;
Begin
S := 'hello Australia morfik France';
Lst := TListReader.Create;
Lst.Readlist(S,' ');
DebugOut(IntToStr(Lst.Count));
For i := 0 To Lst.Count - 1 Do
DebugOut(Lst[i]);
Lst.Free;
End;
{...............................................................................}
[edit] Browser-side solution
{...............................................................................}
TStrList = List of String;
{...............................................................................}
{...............................................................................}
Function ReadList(Lst : String; Delimiter : Char) : TStrList;
{...............................................................................}
Implementation
{...............................................................................}
Function ReadList(Lst : String; Delimiter : Char) : TStrList;
Var
S : TString;
Arr : TArray;
i : Integer;
Begin
Result := Nil;
S := TString(Lst);
Arr := S.Split(Delimiter);
If (Arr <> Nil) And (Arr.length > 0) Then
Begin
Result.Init;
For i := 0 To Arr.length - 1 Do
Result.Add(TString(Arr[i]));
End;
Arr := Nil;
End;
{...............................................................................}
{...............................................................................}
Procedure Index.Button1Click(Event: TDOMEvent);
Var
StrList : TStrList;
i : Integer;
Begin
StrList := ReadList('hello Australia morfik France',' ');
If StrList <> Nil Then
For i := 0 To StrList.Count - 1 Do
ShowMessage(StrList[i]);
End;
{........................................................................}
