Wednesday, June 20, 2018

Delphi - always full of surprises!

After all these years, Delphi still surprises me. Apparently, as I found out today (by making a stupid typo), Copy(string, index, count) doesn't require the count parameter!

IOW, following two lines do exactly the same:

s := Copy('123456789', 4, 6);
s := Copy('123456789', 4);

Works for arrays, too!

Of course, this is not documented.

See for yourself:

program ProjectCopy;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  SysUtils;

var
  s1: TArray;

begin
  Writeln(Copy('123456789', 4, 6));
  Writeln(Copy('123456789', 4));
  s1 := ['1', '2', '3'];
  Writeln(string.Join(',', Copy(s1, 1, 2)));
  Writeln(string.Join(',', Copy(s1, 1)));
  Readln;
end.

This code outputs (in Tokyo):

456789
456789
2,3
2,3

I'd suspect that this goes waaaaaay back. I tested string version with XE2 and it works the same as in Tokyo.

6 comments:

  1. Always good to know, I usually use 1000 as count rather than work out exact length left in a string (somewhat faster). No string in my apps ever exceed 100 let alone a 1000, but its best to be sure. Now I can forget that.

    ReplyDelete
    Replies
    1. You'f better use MaxInt constant instead of 1000. Your string might be more than 1000 characters long.

      Delete
    2. And then some day Delphi enters the modern era and removes the 2GB string limit and now you need to find every instance in your code and change it to avoid truncating large strings. Neither approach is a good idea for this reason.

      Delete
  2. This is indeed pretty old already: both, i.e. that you can omit it and that it works for dynarrays too. But it should be documented.

    ReplyDelete
  3. Well, it doesn't work in Delphi 7.

    ReplyDelete
  4. This is because it is 4 to end of string
    But same in 6 from beginning will not work

    ReplyDelete