简体   繁体   English

Delphi - System.Copy良好实践

[英]Delphi - System.Copy good practices

From my knowledge strings are 1 based in Delphi, 0 position is reserved for the length. 从我的知识字符串是1基于Delphi,0位置是保留的长度。 I am in charge of an huge application written in D5 and D2006, which is using the copy function by copying from the 0 index, and several colleagues are also coding in this way in this moment. 我负责用D5和D2006编写的一个巨大的应用程序,它通过从0索引复制来使用复制功能,并且几个同事也在这个时候以这种方式编码。 Because this is a Delphi 'magic' function, I believe that even if Copy is used to copy the string from 0 index, behind the scenes it copies it from the position 1. 因为这是Delphi的“魔术”功能,我相信即使使用Copy来从0索引复制字符串,在幕后它也会从位置1复制它。

For me a good practice is to copy a string from the 1st position, not from the 0 position, even the result is the same. 对我来说,一个好的做法是从第一个位置复制一个字符串,而不是从0位置,即使结果是相同的。

Now, my question is, can be the application affected when passing to other Delphi version by using the copy function from 0 position instead of be used to copy from 1 position? 现在,我的问题是,通过使用0位置的复制功能而不是用于从1位置复制时传递给其他Delphi版本的应用程序可能受影响吗?

The Delphi RTL ignores you when pass 0 as the Index parameter to Copy for a string. 当将0作为Index参数传递给Copy字符串时,Delphi RTL会忽略您。 When you pass 0 or less for Index , the RTL uses a value of 1 . 当您为Index传递0或更少时,RTL使用值1 So what you are doing is benign in that there are no observable differences in behaviour between passing 1 or any value less than 1. However, it is certainly confusing to use 0 as a string index in Delphi and I would recommend not doing so. 所以你所做的是良性的,因为在传递1或任何小于1的值之间没有可观察到的行为差异。但是,在Delphi中使用0作为字符串索引肯定会令人困惑,我建议不这样做。

In pseudo-code, the implementation of Copy starts like this: 在伪代码中, Copy的实现如下所示:

function Copy(s: string; Index, Count: Integer): string;
begin
  if Index<1 then
    Index := 1;
  dec(Index);//convert from 1-based to 0-based indexing
  ....continues

In fact the actual implementation is a little more complex, but the above pseudo-code gives the correct semantics. 实际上实际的实现稍微复杂一些,但上面的伪代码给出了正确的语义。

Your comment about the length being stored at index 0 is true for old style short strings. 对于旧式短字符串,您对索引0处存储长度的评论是正确的。 But it is not true for long strings. 但对于长串而言,情况并非如此。 In fact it was this very fact that led to the rather odd situation whereby strings are 1-based, but dynamic arrays, lists etc. are 0-based. 实际上正是这个事实导致了相当奇怪的情况,即字符串是基于1的,但动态数组,列表等是基于0的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM