Archive

Posts Tagged ‘Split’

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…

Advertisements
Categories: Delphi, Uncategorized Tags: , ,