Low(字符串)的目的?

问题描述 投票:0回答:1

我正在追踪一些字符编码代码并在

System.SysUtils

中找到了它
function TEncoding.GetBytes(const S: string): TBytes;
var
  Len: Integer;
begin
  Len := GetByteCount(S);
  SetLength(Result, Len);
  GetBytes(S, Low(S), Length(S), Result, 0, Low(S));
end;

Low(S)
在这里做什么?

这里调用的重载

GetBytes()
是:

function TEncoding.GetBytes(const S: string; CharIndex, CharCount: Integer;
  const Bytes: TBytes; ByteIndex: Integer; const StringBaseIndex: Integer): Integer;

这有一个有点神秘的评论:

// StringBaseIndex : Low(string) on caller's context
delphi character-encoding delphi-11-alexandria
1个回答
5
投票

内置函数

Low()
返回可索引项目的较低索引。对于
String
,在最新版本中始终为 1,但在几个版本之前,在移动平台上这将是 0,因此使用
Low()
将允许您编写可在所有平台上编译的代码,无论目标如何。

为了清楚起见,在迭代可索引项的有效索引时,您应该始终使用

Low()
(和
High()
),即使您可能知道(或认为您知道)
Low
和/或
High
是什么值是。让编译器为您确定会更安全。

我见过这样的结构:

for I := 0 to High(Arr) do ...

我的问题始终是,为什么他们使用

High()
然后省略
Low()
- 这对我来说毫无意义。

所以 - 我的建议是始终这样做:

for I := Low(Arr) to High(Arr) do ...

不管你知道什么(或者认为你知道 -

Low(String)
最近从 0 到 1 的变化)。

并且,当迭代

String
中的所有字符时,可以使用:

for C in Str do ...

或:

for I := Low(Str) to High(Str) do ...

High(Str)
与现代编译器中的
Length(Str)
相同,但是当
Low(Str)
为0时,
High(Str)
等于
Length(Str)-1

使用

Low()
High()
也清楚地说明了您的意图,即您正在迭代该项目的所有有效索引。

© www.soinside.com 2019 - 2024. All rights reserved.