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:

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:

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

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.