4

I' m having a function which splits a string by a delimiter:

function ExtractURL(url: string; pattern: string; delimiter: char): string;
var
  indexMet, i: integer;
  urlSplit: TArray<String>;
  delimiterSet: array [0 .. 0] of char;
begin
  delimiterSet[0] := delimiter;
  urlSplit := url.Split(delimiterSet);
  Result := '';

  for i := 0 to Length(urlSplit) - 1 do
  begin
    if urlSplit[i].Contains(pattern) then
    begin
      indexMet := urlSplit[i].LastIndexOf('=') + 1; // extracts pairs key=value
      Result := urlSplit[i].Substring(indexMet);
      Exit;
    end;
  end;
end;

The function works fine when the delimiter is a single character ('&', '|'). How can I pass newline character as delimiter. I tried with #13#10, '#13#10', sLineBreak, Chr(13) + Chr(10) but they don't work.

bob_saginowski
  • 1,429
  • 2
  • 20
  • 35
  • 1
    The delimiter variable is declared as `Char`. If you want multiple delimiter characters, declare delimiter as string. – LU RD Jun 13 '14 at 13:45
  • Remove line feeds, then extract with respect to carriage returns. – Sertac Akyuz Jun 13 '14 at 13:46
  • 1
    Why don't you use a TStringList? This would already split the string on sLineBreak. Have a look here: http://stackoverflow.com/questions/15424293/how-to-split-string-by-a-multi-character-delimiter/15427587#15427587 – Uwe Raabe Jun 13 '14 at 13:52
  • 1
    @SertacAkyuk: There is a `AdjustLineBreaks()` function in the `SysUtils` unit for that purpose. – Remy Lebeau Jun 13 '14 at 14:58
  • @Remy - Thanks, I've never heard of it before. – Sertac Akyuz Jun 13 '14 at 16:57

1 Answers1

1

@TLama first comment on the question solved my problem. I rewrote the function:

function ExtractURL(url: string; pattern: string; delimiter: string): string;
var
  indexMet, i: integer;
  urlSplit: TStringDynArray;
begin
  // note that the delimiter is a string, not a char
  urlSplit := System.StrUtils.SplitString(url, delimiter);
  result := '';

  for i := 0 to Length(urlSplit) - 1 do
  begin
    if urlSplit[i].Contains(pattern) then
    begin
      indexMet := urlSplit[i].LastIndexOf('=') + 1;
      result := urlSplit[i].Substring(indexMet);
      Exit;
    end;
  end;
end;
bob_saginowski
  • 1,429
  • 2
  • 20
  • 35
  • 2
    You can [`shorten it`](http://pastebin.com/ruxqFmDN) a bit. P.S. sorry, but I've deleted my comment since I realized that `SplitString` is not what you're looking for. String helper's `Split` has an overload which takes a string delimiter. – TLama Jun 13 '14 at 14:04