Pages

Friday, September 26, 2014

How to explode some string in delphi

How to explode some string in delphi

In delphi, you can make a function explode as in php, copy the code below to do that :

function explode(const separator, s: string; limit: Integer = 0): TDynStringArray;
var
  SepLen: Integer;
  F, P: PChar;
begin
  SetLength(Result, 0);
  if (S = '') or (Limit < 0) then
    Exit;
  if Separator = '' then
  begin
    SetLength(Result, 1);
    Result[0] := S;
    Exit;
  end;
  SepLen := Length(Separator);

  P := PChar(S);
  while P^ <> #0 do
  begin
    F := P;
    P := AnsiStrPos(P, PChar(Separator));
    if (P = nil) or ((Limit > 0) and (Length(Result) = Limit - 1)) then
      P := StrEnd(F);
    SetLength(Result, Length(Result) + 1);
    SetString(Result[High(Result)], F, P - F);
    F := P;
    while (P^ <> #0) and (P - F < SepLen) do
      Inc(P);
  end;
end;

How to use it? 

To use function above you can call it from button click as example below :
procedure TForm1.Button1Click(Sender: TObject);
var
  ls:string;
  i:integer;
  arr:TDynStringArray;
begin
  ls := 'apple;banana;mango;orange;melon';
  arr := explode(';', ls);
  for i := 0 to Length(arr)-1 do
    ShowMessage(arr[i]);
end;

Thursday, September 25, 2014

How to remove line breaks in delphi

How to remove line breaks from text in Delphi? 

You can use stringreplace function.
  • function StringReplace (const SourceString, OldPattern, NewPattern : string; Flags : TReplaceFlags) : string;
The StringReplace function replaces the first or all occurences of a substring OldPattern in SourceString with NewPattern according to Flags settings. The changed string is returned.

The Flags may be none, one, or both of these set values:
  • rfReplaceAll : Change all occurrences
  • rfIgnoreCase : Ignore case when searching
These values are specified in square brackets.

Below are the sample code :
var
   before, after : string;
begin
   before:='Some text with' + #10#13 + 'line break';
   after := StringReplace(StringReplace(before, #10, ' ', [rfReplaceAll]), #13, ' ', [rfReplaceAll]);
   ShowMessage(before);   
   ShowMessage(after);
end;


Wednesday, September 24, 2014

How to load sql file to ado command

Here is script to load sql file to adocommand at runtime.

var
f:TFileStream;
s:string;
begin
f:=TFileStream.Create('sql_commands.sql',fmOpenRead);
try
SetLength(s,f.Size);
f.Read(s[1],f.Size);
finally
f.Free;
end;
ADOCommand1.CommandText:=s;
Don't Forget To Join Our Community
×
Widget