我有一个简单的功能,可以将数字转换为字符串(类似于Excel列号1..n
可以转换为列名称A-ZZZ
)。当我使用这个很多时,我已经删除了局部变量作为速度优化,并且只能直接使用Result
。如何解决分配字符串到字符串W1047/W1068警告?
当我编译,我得到这2个警告:
W1047不安全的代码 '字符串指数为VAR PARAM' 到位可能不是
W1068修改字符串未来支持
他重新是缩短的功能:
function Idx2Code_(Idx: integer): string;
begin
SetLength(Result, 3); // init Result size
if Idx <= 26 then
begin
// single char: A-Z
Result := Chr(64 + Idx);
SetLength(Result, 1);
end
else if Idx <= 676 then
begin
// 2 chars codes: BA-ZZ
Result[1] := Chr((Idx div 26) + 64 + 1); // <- warnings for this line
Result[2] := Chr((Idx mod 26) + 64); // <- warnings for this line
SetLength(Result, 2);
end
else
begin
// 3 chars codes: BAA-ZZZ
Result[1] := Chr((Idx div 676) + 64 + 1); // <- warnings for this line
Result[2] := Chr(((Idx mod 676) div 26) + 64 + 26); // <- warnings for this line
Result[3] := Chr((Idx mod 26) + 64 + 26); // <- warnings for this line
end;
end;
我可以使用局部变量,但其速度较慢,我不想。
我不想在未来的Delphi版本中使用可能会“过时”的代码。
我该如何解决警告,但尽可能保持简单和速度?
它说'E2129无法分配给只读property'上线'Result.Chars [0]:= CHR(64 + IDX);”。我确实使用了SystemSysutils。我在这里错过了什么? –
我的不好,我忘了'TStringHelper.Chars []'确实是只读的,你不能用它来修改'string'的内容。我会更新我的答案。 –
@MikeTorrettinni,使用[StringBuilder](http://docwiki.embarcadero.com/Libraries/en/SystemUtils.TStringBuilder.Chars) –