2

I'm trying to parse a string with a TStringList:

  sl:=TStringList.Create;
  try
    sl.Text:=aString;
    FFirstRow:=sl[0];
    FSecondRow:=sl[1];
  finally
    sl.Free;
  end;

If aString:='aa'+#13#10+'bb' or aString:='aa'+sLineBreak+'bb' then FFirstRow is aa and FSecondRow is bb. But if aString:='aa\nbb'then FFirstRow gets the whole string (and there is no second row). How do I parse the string with \n as a delimiter?

I tried sl.Delimiter:=Char(13) (and sl.DelimitedText:=aString).

Al C
  • 5,175
  • 6
  • 44
  • 74
  • Since `.Delimiter` is one character and not a String (`\n` are two characters) you can't. But what keeps you from replacing all `\n` occurrances with `#13#10` before? – AmigoJack Feb 14 '21 at 18:03
  • This question is similar to https://stackoverflow.com/questions/15424293/how-to-split-string-by-a-multi-character-delimiter/15427587#15427587 with the same valid answer. – Uwe Raabe Feb 14 '21 at 21:23

2 Answers2

4

The 2-character sequence '\'+'n' is not treated as an escape sequence in Delphi (only in C/C++, and only in compile-time literals, not in runtime data). You will have to replace the sequence manually, such as with StringReplace(), eg:

aString := 'aa\nbb';
sl := TStringList.Create;
try
  sl.Text := StringReplace(aString, '\n', #10, [rfReplaceAll]);
  FFirstRow := sl[0];
  FSecondRow := sl[1];
finally
  sl.Free;
end;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
4

You can just change the string that is treated as the line break in a TStringList:

  sl := TStringList.Create;
  try
    sl.LineBreak := '\n';
    sl.Text := aString;
    FFirstRow := sl[0];
    FSecondRow := sl[1];
  finally
    sl.Free;
  end;
Uwe Raabe
  • 45,288
  • 3
  • 82
  • 130
  • Clever, yet simple. I never would have thought of that (or searched SO in a way that would have brought up your previous answer). – Al C Feb 15 '21 at 19:16