Archive

Archive for the ‘Delphi’ Category

Delphi Split String Utility

April 27, 2012 5 comments

There is no built-in Split function in Delphi, sometimes we need an easy way to perform string splitting just like PHP or Python does: “Hello World”.split(‘ ‘) would produce dynamic array [‘Hello’, ‘World’].

In Delphi you can perform that in different way, for example using TStringList separated text behavior but you need maintenance the TStrings instance each time performing splitting.

var
  Temp: TStrings;
begin
  Temp := TStringList.Create;
  try
    Temp.Text := StringReplace('Hello World', #32, #13#10, [rfReplaceAll]);
    // Process the list here
    // Temp[0] = 'Hello'
    // Temp[1] = 'World'
  finally
    Temp.Free;
  end;
end;

Compare in Python way:

list = 'Hello World'.split(' ')
# list[0] == 'Hello'
# list[1] == 'World'

Pretty short and comfort is it.
I try makes something easy in Delphi way, like this:

var
  List: IStrings;
begin
  List := SplitEx('Hello World', ' ');
  // List[0] = 'Hello'
  // List[1] = 'World'

Or more complex:

  with SplitEx('08:00-13:00, '-') do
  begin
    // Index 0: 08:00
    with SplitEx(Strings[0], ':') do
      // Index 0: 08
      // Index 1: 00
      dtStartTime.Time := EncodeTime(AsInt[0], AsInt[1], 0, 0);

    // Index 1: 13:00
    with SplitEx(Strings[1], ':') do
      // Index 0: 13
      // Index 1: 00
      dtEndTime.Time := EncodeTime(AsInt[0], AsInt[1], 0, 0);
end;

Read more…

Categories: Delphi, Uncategorized Tags: , ,

TSafeMe… BindMe

March 17, 2011 14 comments

Forget Try-Finally to make sure your TObject instance destroyed completely on exit block procedure. TSafeMe makes your code clean without worrying with underlaying memory leaks.

Common try-finally pattern, is this your usual code?

function TXServer.ServiceDelete(const ServiceID: string): IXResponse;
var
  Q_SERVICES: TORM_Q_SERVICES;
begin
  Result := TXResponse.NewResponse();

  Q_SERVICES := TORM_Q_SERVICES.Create; // create new instance
  try
    try
      Q_SERVICES.SERVICE_ID.WhereValue := ServiceID;
      Q_SERVICES.Controller.Delete;
    except
      on E: Exception do
      begin
        Result.RESP_CODE := RC_ERROR;
        Result.RESP_MSG := E.Message;
      end;
    end;
  finally
    Q_SERVICES.Free; // then relese it
  end;
end;

Now compare with this one, see TSafeMe in action: Read more…

Categories: Delphi Tags: