Indexing of Strings

As everyone knows Delphi strings are 1-based. This means that they are starting at the index 1 and ending at the index “Length()”. The reason is that Borland made the huge strings compatible to the old ShortStrings that had a length byte at the position 0.

I have to admit that I’m not happy about this fact since every TList and dynamic array are 0-based. All other important programming languages also have 0-based strings. I guess and also have the impression that EMBT will change this.

Certainly this will break all the old Delphi code. But for new code that you will write in the future you can do it in the way that it will work with 0- and 1-based strings.

Let’s look at an example:

...
var
  I: Integer;
  sBuffer: string;
begin
  sBuffer := 'Hallo World!';
  for I := 1 to Length(sBuffer) do
    Writeln(sBuffer[I]);
  Readln;
end.
...

As you can see there is the “1” and the “Length”. This code only works with 1-based strings. With the help of Low and High you can write it in a more flexible way:

...
var
  I: Integer;
  sBuffer: string;
begin
  sBuffer := 'Hallo World!';
  for I := Low(sBuffer) to High(sBuffer) do
    Writeln(sBuffer[I]);
  Readln;
end.
...

Please consider that Low works for strings in general. This means that you can also write the code in this way:

...
var
  I: Integer;
  sBuffer: string;
begin
  sBuffer := 'Hallo World!';
  for I := Low(string) to High(sBuffer) do
    Writeln(sBuffer[I]);
  Readln;
end.
...

With the help of the new record helpers you can also write it more object-oriented:

...
type
  TStringHelper = record helper for string
  public
    function High: Integer; inline;
    class function Low: Integer; static; inline;
  end;

{ TStringHelper }

function TStringHelper.High: Integer;
begin
  Result := System.High(Self);
end;

class function TStringHelper.Low: Integer;
begin
  Result := System.Low(string);
end;

var
  I: Integer;
  sBuffer: string;
begin
  sBuffer := 'Hallo World!';
  for I := sBuffer.Low to sBuffer.High do
    Writeln(sBuffer[I]);
  Readln;
end.
...

Let’s see which features EMBT will bring to XE4 in the future, please stay tuned…

This entry was posted in Tips and Tricks and tagged . Bookmark the permalink.