-4

I need to split the following string into a TStringList using '|' as the only Delimiter:

" 0.985,EError can't find,E| 0,5186,Name,6946"

Then I need to split each TStringList item using ',' as the only `Delimiter.

So, in the first TStringList would be these items:

" 0.985,EError can't find,E"
"0,5186,Name,6946"

Then, in the second TStringList would be these items:

" 0.985"
"ERror can't find"
"E"

I have to do it without new procedures.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Grow
  • 11
  • 1
  • 3

1 Answers1

4

What you are asking for requires the StrictDelimiter property, which did not exist yet in Delphi 7. Without the StrictDelimiter property, the DelimitedText property setter includes spaces as delimiters regardless of the Delimiter property, and you cannot change that behavior. So, you will have to parse the input string manually instead.

The following code is derived from the StrictDelimiter logic used in later Delphi versions, and works fine in Delphi 7:

uses
  SysUtils, Classes, Windows;

procedure SplitDelimitedText(const Value: string; List: TStrings; StrictDelimiter: Boolean = True);
var
  P, P1: PChar;
  S: string;
begin
  if not StrictDelimiter then
  begin
    List.DelimitedText := Value;
    Exit;
  end;

  List.BeginUpdate;
  try
    List.Clear;
    P := PChar(Value);
    while P^ <> #0 do
    begin
      if P^ = List.QuoteChar then
        S := AnsiExtractQuotedStr(P, List.QuoteChar)
      else
      begin
        P1 := P;
        while (P^ <> #0) and (P^ <> List.Delimiter) do
          P := CharNext(P);
        SetString(S, P1, P - P1);
      end;
      List.Add(S);

      if P^ = List.Delimiter then
      begin
        P1 := P;
        if CharNext(P1)^ = #0 then
          List.Add('');
        P := CharNext(P);
      end;
    end;
  finally
    List.EndUpdate;
  end;
end;

var
  s: String;
  sl1, sl2: TStringList;
  i: Integer;
begin;
  s := ' 0.985,EError can''t find,E| 0,5186,Name,6946';
  sl1 := TStringList.Create;
  try
    sl1.Delimiter := '|';
    sl1.QuoteChar := #0;
    SplitDelimitedText(s, sl1);

    sl2 := TStringList.Create;
    try
      sl2.Delimiter := ',';
      sl2.QuoteChar := #0;
      for I := 0 to sl1.Count-1 do
      begin
        SplitDelimitedText(sl1[i], sl2);
        // use sl2 as needed...
      end;
    finally
      sl2.Free;
    end;
  finally
    sl1.Free;
  end;
end;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770